通过webpack进行Gzip压缩没有发生,缺少了什么

时间:2019-11-03 14:15:04

标签: javascript reactjs typescript webpack

我注意到手动webpack配置和针对同一应用程序/代码库的create-react-app之间的压缩差异,显然create-react-app配置压缩为gzip,因为最终捆绑包的大小比webpack的手动配置小得多,

所以我也尝试使用CompressionPlugin,但似乎无法按预期工作,Webpack配置中可能缺少的内容

const common = require("./webpack.common");
const path = require("path");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const merge = require("webpack-merge");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require('compression-webpack-plugin');
const globImporter = require('node-sass-glob-importer');

module.exports = merge(common, {
    mode: "production",
    output: {
        filename: "[name].[contenthash].js",
        path: path.resolve(__dirname, "dist")
    },
    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                use: [
                    { loader: MiniCssExtractPlugin.loader },
                    { loader: 'css-loader' },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [require('autoprefixer')({
                                'overrideBrowserslist': ['> 1%', 'last 2 versions']
                            })],
                        }
                    },
                    {
                        loader: 'sass-loader', options: {
                            sassOptions: {
                                importer: globImporter()
                            }
                        }
                    }]
            }
        ]
    },
    plugins: [new MiniCssExtractPlugin({
        filename: "./src/css/[name].[contentHash].css"
    },
        new CompressionPlugin({
            algorithm: 'gzip'
        }),
    ), new CleanWebpackPlugin()
    ]

})

1 个答案:

答案 0 :(得分:0)

此代码是过程的一半。现在,您需要告诉express处理这些gzip文件。为此,您需要安装

npm i express-static-gzip

然后在您的server.js中

const expressStaticGzip = require("express-static-gzip");
server.use(expressStaticGzip("dist")); //make sure you use this middleware on top of the other middlewares otherwise it will not work.