bertmaclin
bertmaclin

Reputation: 314

How to use Webpack & Terser to only compress code

I'm attempting to use webpack to compress my code (remove new lines and whitespaces) and nothing else. I don't want any webpack__require__, no mangling, no uglifying, simply just remove whitespace and new lines.

What options in terser/webpack do I have to put to achieve this?

let bundle = {
    mode: 'production',
    target: 'web',
    entry: path.resolve(__dirname, './res/') + '/bundle.js',
    output: {
        path: path.resolve(__dirname, './res/'),
        filename: 'minified.js',
    },
    optimization: {
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    ecma: undefined,
                    warnings: false,
                    parse: {},
                    compress: {},
                    mangle: false,
                    module: false,
                    toplevel: false,
                    keep_classnames: true,
                    keep_fnames: true,
                }
            })
        ]
    }
};

Doesn't seem to do it. Thank you in advance.

Upvotes: 2

Views: 5674

Answers (3)

rpatel
rpatel

Reputation: 734

This will disable compression and use the output option for removing comments. The extractComments property prevents the plugin from extracting comments to a text file.

module.exports = {
    /* ... */
    optimization: {
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    compress: false,
                    output: {
                        comments: false,
                    },
                },
                extractComments: false,
            }),
        ],
    },
};

Upvotes: 1

Matt Goodwin
Matt Goodwin

Reputation: 31

Just to build on felismosh's answer for the CLI you will want to not include the --mangle or --compress commands if all you want to do is remove whitespace and newlines.

So it would be something more like: terser original-file.js -o minified-file.js.

Mangle and compress are disabled unless turned on explicitly in the CLI command.

Upvotes: 2

felixmosh
felixmosh

Reputation: 35613

just use terser directly without webpack. Run npm i terser to install it, then you will have 2 choices:

  1. Using it's cli, terser --compress --mangle -- input.js.

  2. Using it's api from node,

const Terser = require('terser');

const code = {
  'file1.js': 'function add(first, second) { return first + second; }',
  'file2.js': 'console.log(add(1 + 2, 3 + 4));',
};
const options = {
  ecma: undefined,
  warnings: false,
  parse: {},
  compress: {},
  mangle: false,
  module: false,
  toplevel: false,
  keep_classnames: true,
  keep_fnames: true,
};
const result = Terser.minify(code, options);
console.log(result.code);

Upvotes: 0

Related Questions