Webpack: Merge Multiple Javascript Into Single File

Aug 10, 2017

Note: Webpack by default is a module bundler, wrapping each javascript file as a module (cannot be accessed globally by default, resolve modules through import or require statement). If you don't want it to be wrapped as module into a new scope (assuming you want it to be accessed globally outside of the bundle like a standard javascript), refer to [Merge Multiple Javascript Into Single File Global Scope instead.

Group multiple javascripts as single entry point

Edit webpack.config.js to group multiple javascripts as a single named entry.

src/util.js and src/index.js shall be combined into dist/bundle.js.

const path = require('path');module.exports = {  entry: {    'bundle.js': [      path.resolve(__dirname, 'src/util.js'),      path.resolve(__dirname, 'src/index.js')    ]  },  output: {    filename: '[name]',    path: path.resolve(__dirname, 'dist'),  }};

Build.

./node_modules/.bin/webpack

CommonsChunkPlugin

You can utilize CommonsChunkPlugin which is commonly used to store common modules shared by multiple entry points.

In the webpack.config.js below, we would create two bundled js file.

  • app.js which contain our primary app code.
  • vendor.js which consist of shared util code in src/util.js and jquery from npm.
npm install --save-dev jquery
const path = require('path');const webpack = require('webpack');module.exports = {  entry: {    vendor: [      path.resolve(__dirname, 'src/util.js'),      "jquery"    ],    app: path.resolve(__dirname, 'src/index.js')  },  output: {    filename: '[name].js',    path: path.resolve(__dirname, 'dist'),  },  plugins: [    new webpack.optimize.CommonsChunkPlugin({      names: ["vendor"],      // use this to overwrite output config      // filename: "vendor.bundle.js"      // with more entries, this ensures that no other module goes into the vendor chunk      minChunks: Infinity,    })  ]};

NOTE: Refer to webpack configuration to combine Bootstrap dependencies into single js and css file.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.