share react components and include with script tag instead package.json

Viewed 140

I have 3 npm react projects: App1, App2, Shared.

Usecase 1.
In the moment I use npm with lerna and webpack5. App1 and App1 loads the bundle for Shared in package.json: "shared-components": "file:../shared-components" and I can import components from Shared easy with:

import { Button, Headline } from 'shared-components'

and all works fine.

Usecase 2.
Now I have another simple html project(no npm, no react, just plain html and JavaScript):

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Titel </title>
  </head>
  <body>
  <button>button</button>
  <h1>h1</h1>
  </body>
</html>

and want to replace button and h1 with micro react apps:

  • MicroApp1 is a single react project which imports the Button from Shared
  • MicroApp2 is a single react project which imports the Headline from Shared

The problem is now that both MicroApps have a large bundle which includes Shared. The goal is to load the Shared project separately:

<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
</head>
  <body>
  <div id="app1-container"></div>
  <div id="app2-container"></div>
  <script type='text/javascript' src='bundle-of-shared'/>
  <script type='text/javascript' src='bundle-of-app1'/>
  <script type='text/javascript' src='bundle-of-app2'/>
  </body>
</html>

I know about webpack external, dynamic imports and codesplitting but none can implement my use case. The truth is not so simple as described, but rather: How To Gradually Introduce React.js in an Old Application...

Here the code piece from webpack.config of the Shared project:

entry: path.resolve(__dirname, './src/index.js'),
        output: {
            filename: "index.js",
            path: path.resolve(__dirname, 'bundle'),
            libraryTarget: "umd",
        },
        target: ['web', 'es5'],
        module: {
            rules: [
                {
                    test: /\.(js|jsx|es6)$/,
                    use: {
                        loader: 'babel-loader'
                    },
                    exclude: path.resolve(__dirname, 'node_modules/')
                },

Its works fine for Usecase1. I could imagine to change the libraryTarget to use the bundle in a html script tag?

0 Answers
Related