【问题标题】:Webpack TerserPlugin ignoring drop_console in production?Webpack TerserPlugin 在生产中忽略 drop_console?
【发布时间】:2020-09-30 09:26:31
【问题描述】:

将 Webpack 包更新到最新版本后。我注意到 TerserPlugin 在生产中忽略了 console.log 并显示它。

即使在生产中将其设置为 FALSE。

尝试在 Google 和 Github 上查找,但找不到解决方案。

我的 Package.json 依赖项:

"dependencies": {
    "@babel/core": "^7.11.6",
    "@babel/plugin-proposal-class-properties": "^7.10.4",
    "@babel/preset-env": "^7.11.5",
    "@splidejs/splide": "^2.4.14",
    "ascii-art-webpack-plugin": "^0.1.4",
    "autoprefixer": "^10.0.0",
    "babel-eslint": "10.1.0",
    "babel-loader": "^8.1.0",
    "browserslist": "^4.14.3",
    "chokidar": "^3.4.2",
    "clean-terminal-webpack-plugin": "^3.0.0",
    "clean-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^6.1.1",
    "core-js": "^3.6.5",
    "css-loader": "4.3.0",
    "dotenv": "^8.2.0",
    "eslint": "^7.9.0",
    "eslint-loader": "4.0.2",
    "extra-watch-webpack-plugin": "^1.0.3",
    "friendly-errors-webpack-plugin": "^1.7.0",
    "hard-source-webpack-plugin": "^0.13.1",
    "imagemin-mozjpeg": "^9.0.0",
    "imagemin-webpack-plugin": "^2.4.0",
    "mini-css-extract-plugin": "^0.11.2",
    "node-sass": "^4.14.1",
    "postcss": "8.0.7",
    "postcss-100vh-fix": "^1.0.0",
    "postcss-loader": "^4.0.2",
    "postcss-preset-env": "^6.5.0",
    "progress-bar-webpack-plugin": "^2.1.0",
    "sass-loader": "10.0.2",
    "source-map-loader": "^1.1.0",
    "stylelint": "^13.7.1",
    "stylelint-declaration-use-variable": "^1.7.2",
    "stylelint-scss": "^3.18.0",
    "stylelint-use-nesting": "^3.0.0",
    "stylelint-webpack-plugin": "^2.1.0",
    "stylelint-z-index-value-constraint": "^1.1.0",
    "suppress-chunks-webpack-plugin": "^1.0.6",
    "terser-webpack-plugin": "^4.2.2",
    "webpack": "4.44.2",
    "webpack-build-notifier": "^2.1.0",
    "webpack-config-utils": "^2.3.1",
    "webpack-dev-server": "^3.11.0",
    "webpack-manifest-plugin": "^2.2.0",
    "webpack-plugin-hash-output": "^3.2.0",
    "webpack-remove-chunk-entry": "^1.0.0"
},

这是我的 Webpack 插件:

const { THEME_AUTHOR, THEME_NAME, ASCII_TEXT, ASCII_FONT, HOST, PORT } = require('./env.config');

const path = require('path');
const chokidar = require('chokidar');
const paths = require('./paths.config');
const pkg = require('../package.json');
const webpack = require('webpack');
const date = new Date();

// Plugins
const { AsciiArtWebpackPlugin } = require('ascii-art-webpack-plugin');
const HardSourceWebpack = require('hard-source-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtract = require('mini-css-extract-plugin');
const styleLint = require('stylelint-webpack-plugin');
const CopyWebpack = require('copy-webpack-plugin');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
const WebpackBuildNotifierPlugin = require('webpack-build-notifier');
const CleanTerminalPlugin = require('clean-terminal-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const Imagemin = require('imagemin-webpack-plugin').default;
const imageminSvgo = require('imagemin-svgo');
const imageminMozjpeg = require('imagemin-mozjpeg');
const SuppressChunksPlugin = require('suppress-chunks-webpack-plugin').default;

// Config utils
const { removeEmpty, getIfUtils } = require('webpack-config-utils');
const { NODE_ENV } = process.env;
const { ifProduction, ifDevelopment } = getIfUtils(NODE_ENV);

module.exports = {
    target: 'web',
    mode: ifDevelopment ? 'development' : 'production',
    devtool: 'eval-cheap-module-source-map',

    devServer: {
        /**
         * Watch for changes to PHP files and reload the page when one changes.
         */
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        before(app, server) {
            const files = ['**/*.php'];

            chokidar
                .watch(files, {
                    atomic: false,
                    ignoreInitial: true,
                    ignorePermissionErrors: true,
                    persistent: true,
                    usePolling: false
                })
                .on('all', () => {
                    server.sockWrite(server.sockets, 'content-changed');
                });
        },
        quiet: true,
        hot: true,
        historyApiFallback: true,
        open: true,
        writeToDisk: true,
        compress: true,
        public: `http://${HOST}:${PORT}`,
        host: HOST,
        port: PORT,
        proxy: {
            '**': {
                target: `http://${HOST}`,
                secure: false
            }
        }
    },

    stats: {
        colors: true,
        hash: false,
        version: false,
        timings: false,
        assets: false,
        chunks: false,
        modules: false,
        reasons: false,
        children: false,
        source: false,
        errors: false,
        builtAt: false,
        errorDetails: false,
        entrypoints: false,
        warnings: false,
        publicPath: false
    },

    optimization: {
        minimize: ifProduction(true, false),
        namedModules: ifDevelopment(true, false),
        runtimeChunk: 'single',
        noEmitOnErrors: true,
        removeAvailableModules: true,
        removeEmptyChunks: true,
        splitChunks: {
            hidePathInfo: true,
            chunks: 'all',
            maxInitialRequests: 5,
            maxAsyncRequests: 7,
            name: THEME_NAME,
            cacheGroups: {
                default: {
                    enforce: true,
                    priority: 1,
                    minChunks: 2
                },
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    enforce: true,
                    priority: 2
                }
            }
        },

        minimizer: [
            new TerserPlugin({
                test: /\.js(\?.*)?$/i,
                parallel: 4,
                sourceMap: ifDevelopment(true, false),
                terserOptions: {
                    output: {
                        comments: false
                    },
                    compress: {
                        drop_console: ifProduction(true, false)
                    }
                },
                extractComments: false,
                exclude: /\/node_modules/
            })
        ]
    },

    entry: {
        main: [paths.entry.js(), paths.entry.styles()]
        // editor: paths.entry.WPeditor(),
        // admin: paths.entry.WPadmin(),
    },

    output: {
        path: paths.output.base(),
        filename: paths.filename.js()
    },

    module: {
        rules: [
            {
                test: /\.(scss|css)$/,
                exclude: /node_modules/,
                use: [
                    MiniCssExtract.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            url: false
                        }
                    },
                    'postcss-loader',
                    {
                        loader: 'sass-loader',
                        options: {
                            sassOptions: {
                                indentWidth: 4
                            }
                        }
                    }
                ]
            },

            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader', 'eslint-loader']
            }
        ]
    },

    plugins: removeEmpty([
        ifDevelopment(new webpack.HotModuleReplacementPlugin()),

        // new SuppressChunksPlugin([
        //     { name: 'admin', match: /\.js$/ },
        //     { name: 'editor', match: /\.js$/ },
        // ]),

        new CleanWebpackPlugin({
            // Write Logs to Console
            verbose: ifDevelopment(true, false),

            // Automatically remove all unused webpack assets on rebuild
            cleanStaleWebpackAssets: true,

            cleanAfterEveryBuildPatterns: ['!*.+(woff|woff2|eot|ttf|otf|TTF|OTF)'],

            // Do not allow removal of current webpack assets
            protectWebpackAssets: true
        }),

        new styleLint({
            configFile: '.stylelintrc',
            context: paths.styles(),
            files: '**/*.s?(a|c)ss'
        }),

        new MiniCssExtract({
            filename: paths.filename.styles()
        }),

        new CopyWebpack({
            patterns: [
                {
                    from: paths.images(),
                    to: paths.output.images(),
                    noErrorOnMissing: true,
                    globOptions: {
                        dot: false,
                        ignore: ['**/.gitkeep']
                    }
                },

                {
                    from: paths.fonts(),
                    to: paths.output.fonts(),
                    noErrorOnMissing: true,
                    globOptions: {
                        dot: false,
                        ignore: ['**/.gitkeep']
                    }
                }
            ]
        }),

        ifProduction(
            new Imagemin({
                cacheFolder: './.cache-images',
                test: /\.(jpg|jpeg|png|svg)$/i,
                pngquant: {
                    quality: '80-85',
                    speed: 4
                },

                plugins: [
                    imageminMozjpeg({
                        quality: 50,
                        progressive: true
                    }),

                    imageminSvgo({
                        plugins: [
                            {
                                removeViewBox: true,
                                removeTitle: true,
                                removeXMLProcInst: true,
                                removeComments: true,
                                removeMetadata: true,
                                cleanupEnableBackground: true,
                                convertStyleToAttrs: true,
                                convertPathData: true,
                                convertTransform: true,
                                removeUselessStrokeAndFill: true,
                                cleanupIDs: true,
                                moveElemsAttrsToGroup: true,
                                mergePaths: true,
                                convertShapeToPath: true,
                                sortAttrs: true,
                                addClassesToSVGElement: true,
                                reusePaths: true
                            }
                        ]
                    })
                ]
            })
        ),

        new AsciiArtWebpackPlugin({
            text: ASCII_TEXT,
            font: ASCII_FONT,
            extensions: ['js', 'css']
        }),

        new HardSourceWebpack({
            environmentHash: {
                root: process.cwd(),
                directories: [],
                files: ['package-lock.json', 'yarn.lock']
            },

            info: {
                mode: 'none',
                level: 'error'
            },

            // Clean up large, old caches automatically.
            cachePrune: {
                // Caches younger than `maxAge` are not considered for deletion. They must
                // be at least this (default: 2 days) old in milliseconds.
                maxAge: 2 * 24 * 60 * 60 * 1000,
                // All caches together must be larger than `sizeThreshold` before any
                // caches will be deleted. Together they must be at least this
                // (default: 50 MB) big in bytes.
                sizeThreshold: 50 * 1024 * 1024
            }
        }),

        new FriendlyErrorsPlugin(),

        new CleanTerminalPlugin(),

        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
            'process.env.VERSION': JSON.stringify(pkg.version)
        }),

        new webpack.optimize.OccurrenceOrderPlugin(true),

        new webpack.BannerPlugin({
            banner: `Copyright ${date.getFullYear()} ${THEME_AUTHOR} All Rights Reserved - v${
                pkg.version
            }\n${pkg.description}\nLast updated: ${date.getDate()}/${
                date.getMonth() + 1
            }/${date.getFullYear()} (${date.getHours()}:${('0' + date.getMinutes()).substr(-2)})`,
            exclude: /(vendors|runtime)\.js/i
        }),

        ifDevelopment(new webpack.HashedModuleIdsPlugin()),

        ifDevelopment(
            new webpack.SourceMapDevToolPlugin({
                exclude: /(vendors|runtime)\.js/i
            })
        ),

        ifDevelopment(
            new WebpackBuildNotifierPlugin({
                title: `${THEME_AUTHOR}`,
                sound: false,
                suppressSuccess: true
            })
        )
    ])
};

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    想通了。 Devtool 在生产中导致此问题显示所有控制台日志并忽略 Terser 选项 drop_console。

    【讨论】:

    • 什么意思?您知道如何在生产环境中删除 console.logs 吗?
    猜你喜欢
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 2011-05-12
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多