Webpack for component library

1k Views Asked by At

Let's imagine the following structure for a component library:

/my-library
  - /src
    - /components
      - Button.js (ES6 + React)
      - Anchor.js (ES6 + React)
    - index.js (ES6)

Now I want to prepare this library for production, and this is how my distribution folder should look like

/my-library
  - /dist
    - /components
      - Button.js (Target: Node, Compiled to ES5 using babel)
      - Anchor.js (Target: Node, Compiled to ES5 using babel)
    - index.js (Target: browser, compiled and minified with webpack)

Currently I achieve that with two tasks:

1 - One task to "copy" contents from src/components and compile with babel.

2 - Another task to run webpack on src/index.js.

I want to simplify this process and I was told that webpack could be used as the only tool for this process. And this kind of makes sense because src/index.js will go through all the components anyways, why do that twice?

The problem I'm facing is how to provide two different targets for Webpack (node and browser). I think I have an idea how to prepare my entries to output all the components individually, but how to also provide the minified version in a single run?

Any ideas how such webpack configuration should look like?

1

There are 1 best solutions below

7
On

You need rollup.js and not webpack.

For yours components (Button.js, Anchor.js) use rollup-plugin-multi-entry

Example (without multiple entries. Do it by docs from link below)

rollup -c build/rollup.config.js && uglifyjs dist/index.js -cm --comments -o dist/index.min.js

(it's command need add to package.json -> scripts -> "build")

Example rollup.config.js

const buble = require('rollup-plugin-buble')
const flow = require('rollup-plugin-flow-no-whitespace')
const cjs = require('rollup-plugin-commonjs')
const node = require('rollup-plugin-node-resolve')
const replace = require('rollup-plugin-replace')

module.exports = {
  entry: 'src/index.js',
  dest: 'dist/vue-router.js',
  format: 'umd',
  moduleName: 'VueRouter',
  plugins: [replace({
    'process.env.NODE_ENV': '"development"'
  }), flow(), node(), cjs(), buble()]
}