javascriptwebpackecmascript-6webpack-2es6-modules

Output an ES module using webpack


With Rollup I can output an ES module by simply setting the format option to 'es'. How can I do the same with webpack? If it's not possible now, does webpack have any plans to add it?

The only thing I've found in the documentation for output.libraryTarget that mentions ES modules is this:

libraryTarget: "commonjs-module" - Expose it using the module.exports object (output.library is ignored), __esModule is defined (it's threaded as ES2015 Module in interop mode)

However, it's rather unclear to me. Is it the same as libraryTarget: "commonjs2" with the only difference that __esModule is defined? What is "interop mode"?


Solution

  • Webpack2 does not have relevant libraryTarget yet, it does not output ES6 bundles. From the other side If you bundle your library in CommonJS bundlers wont be able to run Tree Shaking, not being able to eliminate unused modules. That's due to ES modules are still developing, so nobody ships ES bundles to browser, while webpack used primarily to create browser enabled bundles.

    From the other side if you are publishing library you can provide both CommonJS (umd) and ES targets, thanks to "module" key in package. json. Actually you do not need webpack to publish ES target, all you need to do is to run babel on every file to get it to es2015 standart, for example if you are using react you can run babel with just "react" preset. If your source is already ES 2015 without extra features you can point module straight to your src/index.js:

    //package.json
    ...
      "module": "src/index.js"
      "main": "dist/your/library/bundle.js
    ...
    

    I found it convenient to use babel to handle export v from 'mod' instructions in my main index.js, so I have 1 module file exporting all my modules. That's achieved with babel-plugin-transform-export-extensions (also included in stage-1 preset).

    I spot this approach from react-bootstrap library, you can see scripts in their github (they are webpack1). I have improved their scripts a little in my react-sigma repo, feel free to copy following files which will do what you need:

    config/babel.config.js
    scripts/buildBabel.js
    scripts/es/build.js
    scripts/build.js // this is command line controller, if you need just ES you don't need it
    

    Also look at lib target (scripts/lib/build.js and .babelrc), I provide lib transpiled modules so library users can include only modules they need even without ES explicitly specifying require("react-sigma/lib/Sigma/"), especially useful if your lib is heavy and modular!