Search code examples
reactjswebpackcode-splitting

Expose components so that they can be dynamically imported in app


I'm building a component library to be imported in an React app. I want to expose these components so that they can be dynamically imported in the app.

What I tried:

lib > index.js

export const Component1 = import(/* webpackChunkName: "components/Component1" */ './components/Component1')
export const Component2 = import(/* webpackChunkName: "components/Component2" */ './components/Component2')

lib > webpack.config.js

entry: path.resolve('src/index.js'),
output: {
    path: path.resolve('build'),
    filename: 'index.js',
    chunkFilename: '[name].js',
    library: 'lib',
    libraryTarget: 'umd'
},

Build result

80.13 KB  build/index.js
69.68 KB  build/components/Component1.js
12.4 KB   build/components/Component2.js

What I want to achieve:

app > index.js

import('lib/components/Component1').then(module => {
    console.log(module) // Empty object so far
})

How am I suppose to export the components so that they are available one by one? Or is there another way?


Solution

  • Finally I succeeded to achieve what I meant by using the configuration defined here: https://github.com/webpack/webpack/tree/master/examples/multi-part-library

    I'm not asynchronously importing the components anymore but set different entries in the webpack config instead.