Webpack
A simple webpack configuration
Webpack is a JavaScript module bundler. Webpack looks at your JavaScript files and "bundles" them with the external libraries that they import. Webpack is also able to understand what parts of a library are not used (when used in a modular format). The new Modular JavaScript SDK is organized so that Webpack will exclude all parts you have not used.
Are you using a framework CLI too like Angular CLI, Vue CLI, or Create React App, or Next.js? Then you don't need to worry about any of this because they handle module bundling for you.
To get started with Webpack first install the tool and a needed plugin.
npm i --save-dev webpack webpack-cli
The
webpack
module contains the main functionality and thewebpack-cli
module is the module that allows you to interface with it from the command line.
Then create a file at the root of your project called webpack.config.js
.
const path = require('path');
module.exports = {
// Set mode to production to see the "tree-shaken" size
mode: "production",
// make sure this points to your entry point file
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
}
};
Then add this command to your "scripts"
section of package.json
.
"scripts": {
"build:js": "webpack"
}
Once that's added run the npm script from the command line.
npm run build:js
Then check the public/bundle.js
for the JavaScript bundle.