Ultimate Guide to Rollup Plugin Terser for JavaScript Minification

Introduction to rollup-plugin-terser

The rollup-plugin-terser is a powerful plugin for the Rollup JavaScript module bundler, designed to minify and optimize your code. The Terser library helps reduce your JavaScript file size, ensuring quicker loading times and better performance for your web applications. In this comprehensive guide, we’ll explore various APIs provided by the rollup-plugin-terser and demonstrate how to integrate them into your project effectively.

Basic Usage

To start using rollup-plugin-terser, first, install it via npm:

  npm install rollup-plugin-terser --save-dev

Then, include it in your Rollup configuration file:

  
  import { terser } from 'rollup-plugin-terser';

  export default {
    input: 'src/index.js',
    output: {
      file: 'dist/bundle.js',
      format: 'cjs'
    },
    plugins: [terser()]
  };
  

API Examples

Configuration

Configure the plugin with custom options:

  
  import { terser } from 'rollup-plugin-terser';

  export default {
    input: 'src/index.js',
    output: {
      file: 'dist/bundle.js',
      format: 'cjs'
    },
    plugins: [terser({
      mangle: {
        toplevel: true,
      },
      compress: {
        drop_console: true
      }
    })]
  };
  

Exclude and Include Files

Minify specific files using the include and exclude options:

  
  import { terser } from 'rollup-plugin-terser';

  export default {
    input: 'src/index.js',
    output: {
      file: 'dist/bundle.js',
      format: 'cjs'
    },
    plugins: [terser({
      include: [/^.+\.js$/],
      exclude: ['node_modules/**']
    })]
  };
  

Source Maps

Generate source maps for easier debugging:

  
  import { terser } from 'rollup-plugin-terser';

  export default {
    input: 'src/index.js',
    output: {
      file: 'dist/bundle.js',
      format: 'cjs',
      sourcemap: true
    },
    plugins: [terser()]
  };
  

App Example

Below is an example of a simple app using rollup-plugin-terser for minification.

  
  // src/index.js
  console.log('Hello, World!');

  // Rollup configuration (rollup.config.js)
  import { terser } from 'rollup-plugin-terser';

  export default {
    input: 'src/index.js',
    output: {
      file: 'dist/bundle.js',
      format: 'cjs'
    },
    plugins: [terser()]
  };

  // package.json
  {
    "name": "rollup-terser-example",
    "version": "1.0.0",
    "scripts": {
      "build": "rollup -c"
    },
    "devDependencies": {
      "rollup": "^2.52.2",
      "rollup-plugin-terser": "^7.0.2"
    }
  }
  

Run the build script to generate a minified bundle:

  npm run build

After running the script, the dist/bundle.js file will be created with the minified code.

Hash: 616664ea0f594b4f505a2fae35528f384ddd703e407b6fe60e43617c9caa9ddb

Leave a Reply

Your email address will not be published. Required fields are marked *