Search code examples
javascriptwebpacklambdabundle

How to Minimize variable names but keep line breaks on Webpack


I am looking a way to minimize the variables and stuff but keep line breaks so the codes are more debugable in my production envirenmnet.

Setting minimize: false will keep original file names. I am working with some Lamda function. So reducing size was expected to increase the invocation time of my fucntions. Adding source maps is expensive on the bundle size. If I could preserve line breaks and introduce a cheap source map, I hope it will reduce overall build size.

** I am using extend to use a base cofig. The attched one is the base config I currently use.**

const path = require('path');

module.exports = {

  target: 'node',
  mode: 'production',
  resolve: {
    extensions: ['.ts', '.js'],
  },

  entry: handlers.reduce(function (obj, el) {
    obj[(path.parse(el).dir+"/"+path.parse(el).name).replace( /^(.\/)?[^/]+\//,"")] = el;
    return obj;
  }, {}),

  output: {
    path: output_dir,
    filename: "[name].js",
    clean: true,

  },
  module: {
    rules: [
      {
        test: /\.ts$/,

        use: [
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
            },
          },
        ],
        exclude: /node_modules/,
      },
    ],
  },
  optimization: {
    minimize: false,
    splitChunks: {
      chunks: 'all', // Split and share code among entries
    },
  },

};

I tried full source-maps and minimize disable so far, Any other suggetions.


Solution

  • You have to use an external minifier (like Terser plugin which is already included in webpack module) as core webpack minifier is not configurable.

    See webpack doc for terser plugin config.

    With Terser, you can achieve keeping line breaks in two ways :

    • Use beautify format option but it seems deprecated
    • Use semicolons format option as it tends to use line breaks instead of semi-colons for line ends in minified output

    Here's an excerpt of a possible webpack configuration :

    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    format: {
                        semicolons : false
                    }
                }
            })
        ]
    }
    

    Link to Full terser API for fine tuning.