I'm new to Webpack and to be honest it still confuses me slightly. I would like to create a shareable UI component library from my react build (Using react-starter-kit as it's base). Is there a way to configure my webpack config to output files that I can then import as an NPM module to another project and import the components?
Current setup source folder:
├── /src/ # The source code of the application
│ ├── /components/ # React components
│ │ ├── /ComponentName # Component
│ │ ├── index.js Exports all components
Using the default setup of react starter kit..it's default webpack.config: https://github.com/kriasoft/react-starter-kit/blob/master/tools/webpack.config.js
If I run the build script as /components/index.js as an entry point the resultant script doesn't give me what I need.
Any ideas?
I handle this in my React component boilerplate in a couple of ways. I've tried to cover the basic ideas below so you can adapt as needed.
dist
versionsSet output.libraryTarget to umd
. This will write a wrapper you can import from various environments (AMD, CommonJS, global). Set output.library
to match the global name of your library.
webpack.config.js
output: {
path: path.join(__dirname, 'dist'),
libraryTarget: 'umd',
library: 'MyAwesomeLibrary'
}
I have set up separate targets for generating a non-minified and a minified version of my component. I include these to the version control when publishing so they are easy for people to find and use.
To make it easy to consume the package through Node and Webpack, I process my code through Babel instead of Webpack. This keeps the file structure intact. Alternatively you could just point to the generated dist
but I find this option neater given it provides more flexibility. You can import features outside of your entry point when doing it like this.
To achieve this, I've set it up as follows:
package.json
"scripts": {
"dist:modules": "babel ./src --out-dir ./dist-modules"
}
This tells Babel to pick up my source and write it to ./dist-modules
. I've .gitignore
d the directory. It will be included only in the published version and generated on demand by a postinstall
script should it not exist. This can happen if you consume a package through version control instead of npm.
These are the basic ideas. Study the boilerplate for more specific details.