如何丑化文件并保存到另一个位置 (vue.js)

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

我不确定如何丑化我的 server.js 文件并将其保存到 server 文件夹下的 dist 文件夹中。现在我正在使用 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']
  }
]),

这有效,但只是一个简单的复制和粘贴。

有一个图书馆已经准备好了。您可以使用 uglifyjs-webpack-plugin

然后将打包后的文件输出到你想要的目录

如果您不喜欢使用该插件。你可以使用 Webpack 的默认丑化器。

const webpack = require("webpack");

    module.exports = {
      entry: {
        "bundle": "./server/server.js",
      }
      output: {
        path: "./dist",
        filename: "[name].js"
      },
      plugins: [
        new webpack.optimize.UglifyJsPlugin({
          include: /\.js$/,
          minimize: true
        })
      ]
    };

您可以使用 uglify-es + copy-webpack-plugin's transform():

  • 安装包:

    npm install uglify-es --save-dev
    
  • 将其添加到您的来源:

    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']
      }
    ]),
    

注:UglifyJS.minify(content.toString()).code等同于UglifyJS.minify(content.toString('utf8')).code.