Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: How do I bundle multiple javascript files into a single output file?

Suppose I have two files, main.js and app.js; how do I use Webpack to bundle both of them into one file: bundle.js?

like image 874
Rish Avatar asked Jul 14 '17 07:07

Rish


People also ask

What is JavaScript bundling?

JavaScript bundling is an optimization technique you can use to reduce the number of server requests for JavaScript files. Bundling accomplishes this by merging multiple JavaScript files together into one file to reduce the number of page requests.

Can you have multiple entry points in a single webpack configuration file?

webpack.config.jsWe can also pass an array of file paths to the entry property which creates what is known as a "multi-main entry". This is useful when you would like to inject multiple dependent files together and graph their dependencies into one "chunk".

How do I include a JavaScript file in webpack?

You can use webpack-inject-plugin to inject any JS code as string into the resulting . js bundle created by webpack. This way you can read the File you want to inject as a string (e.g. fs. readFile in nodejs) and inject it with the plugin.


2 Answers

create one entry.js which is your webpack entry file and in this your require your additional files

webpack.config.js

module.exports = {
   entry: './src/entry.js'
   ...
};

/src/entry.js

// new syntax
import './main.js';
import './app.js';

// or old syntax
require('./main.js');
require('./app.js');

if these two files depend on each other, it would be be beneficial to reflect this in your dependency tree and require main.js in your app.js and not in entry.js for example

like image 148
c0l3 Avatar answered Sep 21 '22 13:09

c0l3


You can pass an array of entries:

module.exports = {
   entry: ['./main.js', './app.js'],
   ...
};

Also, you can pass them as a CLI option:

webpack ./main.js ./app.js --config=webpack.config.js
like image 44
Rodrigo Boniatti Avatar answered Sep 19 '22 13:09

Rodrigo Boniatti