Webpack Export Modules

Multi-Part libraries

You may be working in a complex project, where multiple isolated modules need to be imported into a single parent module, you might want to configure Webpack.config to enable exporting modules.

Maybe you have developed a library and want to distribute it in bundled versions. You want to allow the user to use it in a require or import statement. Or you depend on various precompilations and want to remove the pain for the user and distribute it as simple compiled CommonJS module.

Either scenario, this article will help you to configure your Webpack configurattion.

Configuration Options

Webpack has three configuration options to help you out for these use cases:

  1. output.library – Specify a name for your library
  2. output.libraryTarget – Type of output ie. CommonJS, AMD, UMD
  3. externals – Dependencies for your libraries, to be imported from the environment at runtime

Webpack Example Module

Let’s start off by creating a React component at the src directory and name it index.js.

import React from 'react';

export default const MyApp = () => {
  return (
    <div>
      <h1>My App</h1>
      <p>Hello world!</p>
    </div>
  );
};

The package.json file will look like the following:

{
  "name": "webpack-export-module-demo",
  "version": "1.0.0",
  "description": "Webpack demo for exporting a module",
  "main": "index.js",
  "scripts": {
    "build:webpack": "webpack --config webpack.config.js",
    "build": "npm run build:webpack",
    "prepublish": "npm run build"
  },
  "keywords": [
    "Webpack"
  ],
  "author": "Sean Amarasinghe",
  "license": "ISC",
  "dependencies": {
    "react": "^15.1.0"
  }
}

The webpack.config.js file will have library and libraryTarget properties.

var webpack = require('webpack');
var UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');

module.exports = {
    context: __dirname + '/src/',
    entry: './index.js',
    output: {
        path: __dirname + '/dist/',
        filename: 'bundle.js',
        library: 'my-app',
        libraryTarget: 'commonjs2'
    },
    module: {
        loaders: [
            {
              test: /\.js$/,
              loader: 'babel-loader'
            }
        ]
    },
    externals: {
        react: {
            root: 'React',
            commonjs: 'react',
            commonjs2: 'react',
            amd: 'react'
        }
    },

    plugins: [
        new UglifyJsPlugin()
    ]
};

We provided a name for the library, my-app and the libraryTarget commonjs2. If you selected commonjs instead of commonjs2, you will have default as the container object, which you might not want.

Now you can import this library into another project.

Conclusion

You can find the source code for this article in Github.

Be first to comment

Leave a Reply