This article goes over how to get started with webpack.
Background
Given a module that returns the sum of 2 numbers:
// src/add.js
module.exports = function add(a, b) {
return a + b;
};
// src/index.js
var add = require('./add');
console.log('2 + 2 =', add(2, 2));
console.log('1 + 1 =', add(1, 1));
Running the module on Node.js works:
node src/index.js
2 + 2 = 4
1 + 1 = 2
But what if you want to load the module in your browser?
<!-- index.html -->
<script src="src/index.js"></script>
Since the browser doesn’t understand CommonJS, you’ll need to bundle your modules.
Install
Install webpack and webpack-cli:
npm install webpack webpack-cli --save-dev
Your package.json
will look like:
{
"devDependencies": {
"webpack": "^5.36.2",
"webpack-cli": "^4.6.0"
}
}
CLI
Build the bundle with the CLI:
npx webpack
By default, the entry point is
./src/index.js
and the output is./dist/main.js
.
Update the script tag:
<!-- index.html -->
<script src="dist/main.js"></script>
You should see the logs in your browser console:
open index.html
Configuration
Instead of passing options to the CLI, create a configuration file:
// webpack.config.js
const { resolve } = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: resolve(__dirname, 'dist'),
filename: 'main.js',
},
};
Webpack uses webpack.config.js
if it exists:
npx webpack