Search code examples
node.jswebpackvue.jsvuejs2webpack-2

how to uglify a file and save to another location (vue.js)


I am unsure on how to uglify my server.js file and save it into the dist folder under a server folder. Right now I'm just using the CopyWebpackPlugin

new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetsSubDirectory,
    ignore: ['.*']
  },
  {
    from: path.resolve(__dirname, '../src/server'),
    to: config.build.assetsServerDirectory,
    ignore: ['*.sql']
  }
]),

This works, but is just a simple copy and paste.


Solution

  • You can use uglify-es + copy-webpack-plugin's transform():

    • Install the package:

      npm install uglify-es --save-dev
      
    • Add it to your source:

      const UglifyJS = require("uglify-es");                  // add the require
      
      new CopyWebpackPlugin([
        {
          from: path.resolve(__dirname, '../static'),
          to: config.build.assetsSubDirectory,
          ignore: ['.*']
        },
        {
          from: path.resolve(__dirname, '../src/server'),
          to: config.build.assetsServerDirectory,
          transform: function (content, path) {               // add transform()
            return UglifyJS.minify(content.toString()).code;  // use uglify
          },                                                  // (no args = mangle+compress)
          ignore: ['*.sql']
        }
      ]),
      

    Note: UglifyJS.minify(content.toString()).code is the same as UglifyJS.minify(content.toString('utf8')).code. There are options in case of different encodings.