How to set up Webpack to minify JavaScript files with Terser
Webpack is a powerful tool for bundling JavaScript, CSS, and other assets in modern web development. One important feature of Webpack is its ability to optimize and minify code to improve performance and reduce file size. Terser is a popular JavaScript minifier that can be used with Webpack to reduce the size of JavaScript files.
Terser is a JavaScript parser and minifier that can remove unnecessary code, shorten variable names, and perform other optimizations to reduce the size of JavaScript files. Terser can be used with Webpack to minimize the size of JavaScript code in the final build.
To set up Webpack to minify JavaScript files with Terser, you can follow these steps:
- Install Terser and Webpack via npm:
npm install terser webpack --save-dev
- Configure Webpack to use Terser by adding the following code to your
webpack.config.js
file:
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.min.js',
path: __dirname + '/dist',
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
};
In the above example, we import the TerserPlugin
from the terser-webpack-plugin
module and add it to the minimizer
array in the optimization
object. This tells Webpack to use Terser to minimize the JavaScript code during the build process.
3. Run webpack to build your project with the minified code:
webpack --mode production
This will run Webpack in production mode and use Terser to minimize the JavaScript code. The output will be a minified bundle.min.js
file located in the dist
directory.
How to configure Terser minification options
Here’s an example of how to customize Terser options in the webpack.config.js
file:
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.min.js',
path: __dirname + '/dist',
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
},
mangle: true,
},
}),
],
},
};
In the above example, we set the drop_console
option to true to remove any console statements in the code and the mangle
option to true to rename variables and functions. These options are passed to Terser via the terserOptions
object.
Conslusion
Using Webpack with Terser is a great way to optimize and reduce the size of your JavaScript code, resulting in faster page load times and improved user experience. With the step-by-step instructions and code examples provided in this tutorial, you should now have the knowledge you need to get started with Webpack and Terser. Remember to experiment with different Terser options to find the best configuration for your project. By implementing these techniques, you can ensure that your web application is fast and efficient, making it more appealing to users and search engines alike.
Published on Feb 27, 2023 by Oleh Pratsko