webpack/terser: How can I exclude a package from minification, but still include that package in the packed result?

1.2k views Asked by At

I've found a number of solutions for excluding particular modules from minification, but all of the solutions I've seen so far not only skip minification of those packages, they cause those packages to be completely omitted from webpack's output, requiring you to provide the omitted code by some other means.

What I want to do is continue to package all needed code into one single output file, but simply have sections of that output non-minified. Is that possible?

The reason that I want to do this in this particular case is that the mysql package is failing after minification. For the moment I've disabled all minification, but I'd rather not solve this problem that way.

const webpack = require('webpack');
const LicensePlugin = require('webpack-license-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
const mode = process.env.NODE_ENV || 'production';

// noinspection JSUnresolvedFunction
module.exports = {
  mode,
  entry: './app/app.ts',
  target: 'node',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'
  },
  node: {
    __dirname: false,
    __filename: false,
    global: true
  },
  resolve: {
    extensions: ['.ts', '.js'],
    mainFields: ['fesm2015', 'module', 'main']
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          'ts-loader',
        ]
      }
    ]
  },
  optimization: {
    // TODO: Minification breaks mysql. How to exclude mysql from minification, but include in output?
    minimize: false, // mode === 'production',
    minimizer: [new TerserPlugin({
      exclude: /node_modules\/mysql/, // <-- This doesn't work
      terserOptions: {
        output: { max_line_len: 511 },
      }
    })],
  },
  devtool: 'source-map',
  ignoreWarnings: [{ message: /require function is used in a way|the request of a dependency is an expression/ }],
  plugins: [
    new webpack.BannerPlugin({ banner: '#!/usr/bin/env node', raw: true }),
    new LicensePlugin({
      outputFilename: '3rdpartylicenses.txt',
      excludedPackageTest: name => /^(asynclist|emitter)/.test(name)
    })
  ]
};

Update: The particular issue with mysql and minification seems to be mangling of variable and/or function names. If I set the mangle option to false, I can minify all of the code, including mysql, successfully. I have yet to figure out which specific names can't be mangled without causing problems.

0

There are 0 answers