简体   繁体   English

如何使用 TerserPlugin 和 webpack-encore 进行压缩

[英]How to minify with TerserPlugin and webpack-encore

With this webpack.config.js that use webpack-encore, and minify with terser, I can compile successfully, but absolutely nothing is minified at all.使用这个使用 webpack-encore 并使用 terser 缩小的 webpack.config.js,我可以成功编译,但绝对没有任何东西被缩小。 Comments, and full variable names, are still there.注释和完整的变量名仍然存在。

var Encore = require('@symfony/webpack-encore');

const TerserPlugin = require('terser-webpack-plugin');

Encore
    // the project directory where compiled assets will be stored
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    // the public path used by the web server to access the previous directory
    .cleanupOutputBeforeBuild()
    .enableSourceMaps(!Encore.isProduction())
    .enableReactPreset()
    .enableSassLoader()
    .enableLessLoader()
    .autoProvidejQuery()
    .disableSingleRuntimeChunk()

     .addEntry('app_prescription', [
         './assets/js/prescription/app_prescription.js'
     ])



    .addLoader({
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: "babel-loader?cacheDirectory"
    })

;


if( Encore.isProduction() ) {
    Encore.addPlugin(new TerserPlugin({parallel: true,cache:true}) );
}

module.exports = function(env) {

    Encore.enableVersioning();
    const config = Encore.getWebpackConfig() ;

    if( Encore.isProduction() ) {

        config.optimization = {
            minimizer: [new TerserPlugin({parallel: true,cache:true})]
        }
    }



    return config ;
}

What is wrong with this code?这段代码有什么问题?

Late answer for everyone who stumbles upon this in 2021 and later:对于在 2021 年及以后偶然发现此问题的每个人的迟到答案:

Use encore's configureTerserPlugin method:使用 encore 的configureTerserPlugin方法:

 Encore.configureTerserPlugin((options) => {
     options.cache = true;
     options.terserOptions = {
         output: {
             comments: false
         }
     }
 })

Accordingly to https://github.com/webpack-contrib/terser-webpack-plugin#extractcomments to avoid generating *.LICENSE.txt files you should use this option of method:根据https://github.com/webpack-contrib/terser-webpack-plugin#extractcomments为避免生成*.LICENSE.txt文件,您应该使用以下方法选项:

Encore.configureTerserPlugin(options => {
    options.extractComments = false;
});
const TerserPlugin = require('terser-webpack-plugin');

Encore.configureTerserPlugin((options) => {
    options.extractComments = false;
    options.terserOptions = {
        output: {
            comments: false,
        },
    };
});

// Minify code
const optimization = {
    minimize: true,
    minimizer: [
        new TerserPlugin(),
    ],
}

... // other encore code in here

module.exports = {
    ...Encore.getWebpackConfig(),
    name: config.name,
    optimization,
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM