【问题标题】:compression webpack bundle using plugin使用插件压缩 webpack 包
【发布时间】:2018-09-25 10:58:42
【问题描述】:

我正在尝试使用 CompressionPlugin 压缩 webpack 包。 在我的 webpack 设置下方

网络包

const path = require('path');
const webpack = require('webpack');

const CompressionPlugin = require("compression-webpack-plugin")


module.exports = {
entry: ['babel-polyfill', './src/client.js'],
output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'public')
},

plugins: [
    new webpack.DefinePlugin({ 
        'process.env': {
        'NODE_ENV': JSON.stringify('production'),

        }
    }),
    new webpack.optimize.UglifyJsPlugin({
                output: {
                    comments: false,
                    beautify: false,
                },
                compress: {
                    screw_ie8: true,
                    warnings: false
                    }
                }),
    new webpack.optimize.AggressiveMergingPlugin(),
    new CompressionPlugin({   
        asset: "[path].gz[query]",
        algorithm: "gzip",
        test: /\.js$|\.css$|\.html$/,
        threshold: 10240,
        minRatio: 0.8
    })
],
watch: true,
module:{
    loaders:[
        {
            test:/\.js$/,
            exclude:/node_modules/,
            loader: 'babel-loader',
            query:{
                presets: ['react','es2015','stage-1'],
            },
        },
    ],
},
};

www

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);


var server = http.createServer(app);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

index.ejs

<body>
    <DIV id="app"><%- reactComponent -%></DIV>
    <script>window.INITIAL_STATE=<%- initialState -%></script>
    <SCRIPT src="/bundle.js"></SCRIPT>
</body>
</html>

我得到以下捆绑输出

似乎一切正常,但我不确定我是否以正确的方式进行操作, 我不确定它是否真的配置为使用 bundle.js.gz

【问题讨论】:

    标签: javascript node.js reactjs webpack bundle


    【解决方案1】:

    当浏览器调用到达服务器时,它必须启用gzip 编码:请求标头必须包含以下内容:

    Accept-Encoding: gzip, deflate, br 所有浏览器support this,但较旧的浏览器可能没有它。

    您无需添加任何额外的script 标签即可使其正常工作。您引用了js 文件。

    您正在使用节点 http 服务器提供文件,除非直接访问,否则该服务器不知道如何处理 gzip 文件。

    当收到一个可以处理gzip 的请求时,服务器应该检查请求的文件是否也有它的存档版本并提供它。

    我还没有测试过this implementation,但它似乎正在做你需要的事情:你必须调整你的节点服务器。

    使用nginx 或Apache 提供文件时,启用gzip 是一项设置。

    希望对你有帮助

    【讨论】:

    • 所以我们需要部署一个同时包含 bundle.js 和 bundle.js.gz 文件的项目?
    • 如果您正在测试 this node implementation,不,您不必部署 gz,因为这将根据请求生成 - 不理想。如果您使用nginx 或类似名称提供静态文件,是的,您必须部署gz 文件。
    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 2014-11-15
    • 2016-04-22
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    相关资源
    最近更新 更多