webpack打包的.gz文件,怎么在浏览器页面中引用

clipboard.png

做的是 react 项目,在 webpack 中利用压缩插件 compression-webpack-plugin 将
main.bundle.js 压缩成了 main.bundle.js.gz ,看起来是边小了,但是在从服务器上取下来的还是之前的 main.bundle.js ,问大牛们,怎么才能取到 main.bundle.js.gz 这个压缩后的文件?取到 .gz 文件了,浏览器能正常解析吗?或者说,到底怎么用 compression-webpack-plugin 插件?

clipboard.png

下面是我的 webpack 部分配置文件:

const webpack = require('webpack');
const path = require("path");
const ConfigPath = require("./build/common/configPath");  // 配置路径文件
const htwx = path.resolve(__dirname, "htweixin1/");

// 插件
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');  

module.exports = {
    entry: {  //唯一入口文件,就像Java中的main方法
        vendor: ['react', 'react-dom', 'mobile-select', 'jquery'],
        tools: [__dirname + '/src/components/tools/myTools.js', __dirname + '/src/components/tools/newTools.js'],
        main: __dirname + '/src/main.js'
    },
    output: {//输出目录
        path: htwx,//打包后的js文件存放的地方
        publicPath: '/weixin/',
        filename: "dist/js/[name].bundle.js",  //打包后的js文件名
        chunkFilename: "dist/js/[name].min.js"
    },
    module: {
        rules: [
            {
                test: /(\.jsx|\.js)$/,
                use: {
                    loader: "babel-loader"
                },
                exclude: /node_modules/
            }, {
                test: /^((?!\.sinosoft).)*(css)$/,
                use: ["style-loader",
                    {
                        loader: "css-loader",
                        options: {
                            importLoaders: 1,  // 在 css-loader 前应用的 loader 的数
                            modules: false,   // 启用 css-module 模式
                            minimize: true,  // css 压缩
                        }
                    },
                    {
                        loader: "postcss-loader",  // 如果没有 options 这个选项将会报错 No PostCSS Config found
                        options: {
                            plugins: (loader) => [
                                require("autoprefixer")({ broswer: 'last 5 versions' })  // 自动加前缀
                            ]
                        }
                    }],
            }, {
                test: /\.sinosoft\.css$/,
                use: ["style-loader",
                    {
                        loader: "css-loader",
                        options: {
                            importLoaders: 1,  // 在 css-loader 前应用的 loader 的数
                            modules: false,   // 启用 css-module 模式
                            minimize: true,  // css 压缩
                        }
                    }],
            }, {
                test: /\.(png|jpe?g|gif|svg|bmp)$/,
                use: [{
                    loader: "url-loader",
                    options: {
                        limit: 10240, // 10KB 以下使用 base64
                        name: "dist/images/[name]-[hash:6].[ext]",
                    }
                }]
            }
        ]
    },
    resolve: {
        extensions: ['.js', ".css", '.jsx'],  //自动补全识别后缀
        // 自定义常用文件路径
        alias: {
            CSS: path.join(ConfigPath.static, 'css'),
            IMAGES: path.join(ConfigPath.static, 'images'),
            JS: path.join(ConfigPath.static, 'js'),
            COMMON: path.join(ConfigPath.src, 'components/common'),
            LAYOUT: path.join(ConfigPath.src, 'components/layout'),
            PAGE: path.join(ConfigPath.src, 'components/page'),
            TOOLS: path.join(ConfigPath.src, 'components/tools'),
            DATAMODULE: path.join(ConfigPath.static, "data"),
        }
    },
    plugins: [
        // 定义全局变量
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': '"production"'
        }),
        // 将代码中有重复的依赖包去重
        new webpack.optimize.DedupePlugin(),
        // 为组件分配ID,通过这个插件webpack可以分析和优先考虑使用最多的模块,并为它们分配最小的ID
        new webpack.optimize.OccurrenceOrderPlugin(),
        // 压缩JS代码
        new webpack.optimize.UglifyJsPlugin(),
        // 公共代码分离打包
        new webpack.optimize.CommonsChunkPlugin({
            name: [ "main", "tools", "vendor"],
            filename: "dist/js/[name].bundle1.js",
            chunkFilename: "dist/js/[name].chunk.js",
            minChunks: function (module) {
                // 该配置假定你引入的存在于 node_modules 目录中
                return module.context && module.context.indexOf('node_modules') !== -1;
            }
        }),
        //为了避免vendor.*.js的hash值发生改变需要输出一个manifest.*.js文件
        new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest', //But since there are no more common modules between them we end up with just the runtime code included in the manifest file
            filename: "dist/js/[name].manifest.js",
        }),

        // 自动生成一个 index.html 文件,并在 html 文件中引用 bundle.js 和 *.css 文件
        new HtmlWebpackPlugin({
            template: __dirname + "/build/template.tpl.html", //new 一个这个插件的实例,并传入相关的参数
            filename: htwx + "/index.html",
            inject: true, // 自动注入
            minify: {  // 代码压缩
                removeComments: true,         // 删除html中的注释代码
                collapseWhitespace: true,     // 删除html中的空白符
                removeAttributeQuotes: true   // 删除html元素中属性的引号
            },
            //必须通过上面的 CommonsChunkPlugin 的依赖关系自动添加 js,css 等
            chunksSortMode: 'dependency'
        }),

        //gzip 压缩
        new CompressionWebpackPlugin({
            asset: '[path].gz[query]',   // 目标文件名
            algorithm: 'gzip',   // 使用gzip压缩
            test: new RegExp(
                '\\.(js|css)$'    // 压缩 js 与 css
            ),
            threshold: 10240,   // 资源文件大于10240B=10kB时会被压缩
            minRatio: 0.8  // 最小压缩比达到0.8时才会被压缩
        }),

        // css 代码分离
        new ExtractTextPlugin("dist/css/[name]-[hash:3].css"),

        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require('./manifest.json'),
        }),

        // 自定义插件
        (function () { }).prototype.apply = function (compiler) {
            console.log("\u4e0d\u662f\u6211\u9a97\u4f60\uff0c\u4eba\u4e11\u5c31\u8981\u591a\u8bfb\u4e66")
        },
        new webpack.BannerPlugin('author: Mobro Zhu'),

        // jQuery插件
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery"
        }),
    ],
};
阅读 16.7k
6 个回答

你的服务器是用的nginx还是什么?别说直接是node.

假设你们用的是nginx,那么这个要在nginx里面启用 ngx_http_gzip_static_module:

gzip_static  on;

具体的配置请参考这里:http://nginx.org/en/docs/http...

服务端要进行配置,比如 nginx,在你的匹配路径中配置:

gzip on;
gzip_disable "msie6";
gzip_buffers 32 4k;
gzip_static on;

最主要的是gzip_static on;这一句,nginx 会优先匹配你的 gzip 文件来返回,如果没有就寻找相应资源进行 gzip 压缩再返回。

gz文件是在网络传输时候减小网络开销用的,如何请求的话在服务器配置开启gzip,请求会优先匹配同文件名的gz压缩格式返回,浏览器拿到之后会自动解压,你引用的是解压后的js或css文件

请问,这个压缩后的文件怎么引用的呢?

你有明确请求gz文件吗,或者在服务器做了重定向?

在IIS7中只需要将该站点压缩功能选择为“应用”就可以了,要注意页面请求后的Response Headers中的Content-Encoding的值为“gzip”,Request Headers中Accept-Encoding的值存在“gzip”值就可以了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题