Multiple Entries

Bharat Tiwari
A beginner’s guide to Webpack 2
2 min readMay 7, 2017

Sometimes you may want to package your javascript files into multiple bundles.

For example, we may want to create two bundles –app.bundle.js for all our application-specific code, and another bundle vendor.bundle.js for all our npm dependencies and include the two bundles in two separate <script> tags in your index.html. Lets how we can configure webpack to achieve this.

  1. First, lets add ‘lodash’ as a dependency to our application
npm install lodash --save

2. Let’s use lodash in our app.js. Update the app.js code as below:

Above, we are importing ‘lodash’ in app.js and then using its _.each function to iterate over a local array, logging the value of each element in the array to console.

3. Now update the webpack.config.js as below:

Lets go over the changes we made above to webpack.config.js

a. In the above code, we imported thepackage.json (line # 2).

b. Next, we changed the value for entry property from a string to an object with two keys – app and vendor.
What this would mean to webpack is to start bundling the modules from two entry points – 1. ‘app’ i.e. from ‘./src/scripts/app.js’ and 2. start bundling the npm modules listed in package.dependencies i.e. package.json’s dependencies section.

c. We updated the value for output.filename to ./dist/[name].bundle.js.
When webpack creates the output bundle file for each of the entry points specified, the [name] part of this output.filename value would be replace by the entry point’s key name i.e. app and vendor thus creating two files – app.bundle.js and vendor.bundle.js.

4. Run npm start for webpack to run with the updated config options.

$ npm start

5. This time you wound notice webpack created two expected bundled files for us — app.bundle.js and vendor.bundle.js.
HtmlWebpackPlugin would embed two <script> tags for us for these two bundle files in its generated index.js file

(click on image to see in expanded popover view)

6. Refresh the browser, the console log now should show the logs we have coded inside _.each.

Thus we are able to configure webpack to make multiple bundles of our app modules based on the multiple entry points we specify in webpack.config. In the next section, we will see how to configure webpack to generate multiple html pages.

--

--