Webpack output is empty object

后端 未结 1 1856
面向向阳花
面向向阳花 2020-11-29 09:33

I want to build a react component library as a node module to then import it into different projects. But if I try to import a component it just returns an empty object.

相关标签:
1条回答
  • 2020-11-29 09:53

    A webpack bundle does not expose your exports by default, as it assumes that you're building an app and not a library (which is the far more common use of webpack). You can create a library by configuring output.library and output.libraryTarget.

    output: {
       path: __dirname,
       filename: 'bundle.js',
       library: 'yourLibName',
       libraryTarget: 'commonjs2'
    },
    

    output.libraryTarget is the format of the module, which would also allow you to expose the library as a global variable. commonjs2 is the module format that Node uses. See What is commonjs2? for the difference between commonjs and commonjs2.

    Since you're using React, you'll expect that the consumer of the library will have React present as a dependency and therefore you don't want to include it in your bundle. To do that you can define it as an External. This is shown in Authoring Libraries, which walks you through a small example.

    0 讨论(0)
提交回复
热议问题