Introduction to rollup-plugin-terser
rollup-plugin-terser
is a powerful plugin for Rollup that minifies and compresses JavaScript bundles, making them smaller and faster to load. It leverages the Terser library,
a modern JavaScript minifier capable of handling ES6+ syntax. Implementing this plugin can significantly improve your application’s performance and search engine optimization (SEO).
Getting Started
To begin, you need to install the plugin:
npm install rollup-plugin-terser --save-dev
Basic Usage
Incorporate rollup-plugin-terser
into your Rollup configuration to start minifying your JavaScript files:
import { terser } from "rollup-plugin-terser";
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [terser()]
};
Advanced Options
Customize the Terser configuration with various options:
import { terser } from "rollup-plugin-terser";
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
terser({
mangle: {
toplevel: true,
},
compress: {
drop_console: true,
},
})
]
};
Examples of Useful API
Here are examples of some useful Terser API options:
Compress Options
Remove debugger statements, drop console logs, and more:
terser({
compress: {
drop_debugger: true,
drop_console: true,
passes: 2
}
});
mangle Options
Advanced variable renaming for better compression:
terser({
mangle: {
properties: {
regex: /^_/
}
}
});
Output Options
Beautify the output for specific requirements:
terser({
output: {
beautify: true,
}
});
Real-World Application Example
Let’s implement a real-world example using rollup-plugin-terser
in a sample project:
// Sample Project Setup
// Directory Structure:
// - src
// --- main.js
// --- module.js
// - rollup.config.js
// src/main.js
import { greet } from './module';
const message = greet('World');
console.log(message);
// src/module.js
export function greet(name) {
return `Hello, ${name}!`;
}
// rollup.config.js
import { terser } from "rollup-plugin-terser";
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [terser({
mangle: {
toplevel: true,
},
compress: {
drop_console: true,
},
})]
};
This configuration will take the files from the src
directory, minify them using Terser, and output a compressed version in the dist
directory.
Conclusion
Using rollup-plugin-terser
can drastically reduce the size of your JavaScript bundles and improve load times, which is beneficial for both user experience and SEO. Given its extensive range of customizable options, you can fine-tune the plugin to meet the specific needs of your project.
Hash: 616664ea0f594b4f505a2fae35528f384ddd703e407b6fe60e43617c9caa9ddb