Starting from version 4, webpack can operate without a configuration file, but for most projects that require more advanced setups, webpack provides support for a configuration file. Utilizing a configuration file is considerably more efficient than manually entering numerous commands in the terminal. Let's explore how we can work with the webpack config file:
Start by creating a file named webpack.config.js
in the root directory of your project. This file will hold all the configuration settings for webpack.
In the webpack.config.js
file, we need to export a JavaScript object containing the configuration options. We can use the CommonJS module syntax to export the object.
Specify the entry point for your application, which is the starting point for webpack to build our dependency graph. We can define it using the entry
property in the config object:
module.exports = {
entry: './src/index.js',
};
Define the output configuration, which determines where the bundled code will be generated. Specify the output path and filename using the output
property:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
In this example, the bundled code will be generated in the dist
directory with the filename main.js
.
<aside> 🧠This is the default configuration webpack uses when a configuration file is not present.
</aside>
Let’s adjust our package.json
file to include a build script that will run webpack for us moving forwards.
{
// Other configuration options
"scripts": {
"build": "webpack --config webpack.config.js"
},
}
<aside>
📦 If a webpack.config.js
 is present, the webpack
 command picks it up by default. We use the --config
 option here only to show that you can pass a configuration of any name. This will be useful for more complex configurations that need to be split into multiple files.
</aside>
Now, let's run the build again but instead using our new configuration file:
pnpm build
Inspect the dist/main.js
file and you will find a minified and optimized JavaScript file produced by webpack for us.
In conclusion, understanding the basics of bundling JavaScript using webpack is a crucial skill for modern web development. By leveraging webpack's powerful features, we can efficiently manage dependencies, optimize our code, and create a streamlined bundle for our web applications. We covered the fundamental concepts of webpack and learned how to setup a basic webpack configuration.