Nginx 如何正确压缩网页包块?

Nginx 如何正确压缩网页包块?,nginx,webpack,gzip,http-compression,webpack-splitchunks,Nginx,Webpack,Gzip,Http Compression,Webpack Splitchunks,我已经在构建一个配置为禁用gzip压缩的工作web应用程序 我使用HtmlWebpackPlugin将Vue内容和生成的块(js和css)注入主index.html 块由Webpack 4的splitChunks指令创建 我现在想要的是激活CompressionWebpackPlugin,以缩小我的大输出文件 如果没有块,压缩插件会做得很好。它为每个块创建一个*.js.gz文件,但不会将每个块中的引用更新为其他块 因此,浏览器将无法找到所有需要的文件 例如,index.html中有一个或两个对c

我已经在构建一个配置为禁用gzip压缩的工作web应用程序

我使用
HtmlWebpackPlugin
将Vue内容和生成的块(js和css)注入主
index.html

块由Webpack 4的
splitChunks
指令创建

我现在想要的是激活
CompressionWebpackPlugin
,以缩小我的大输出文件

如果没有块,压缩插件会做得很好。它为每个块创建一个
*.js.gz
文件,但不会将每个块中的引用更新为其他块

因此,浏览器将无法找到所有需要的文件

例如,
index.html
中有一个或两个对
chunk1.js.gz
chunk2.js.gz
的引用,但在
chunk1
chunk2
中有许多对其他块的引用,这些引用无法找到,因为引用的结尾是
.js
,而实际文件的结尾是
.js.gz

如何正确配置
CompressionWebpackPlugin
(或任何其他整个网页包设置和插件),以便它们相应地更新文件引用

这怎么可能是完全动态的,这样我甚至可以使用最小比率或最小文件大小的压缩功能?(然后一些输出块将是
.js
,一些将是
.js.gz
,因此一些引用必须是第一个选项,一些引用必须是第二个选项)

对类似问题的其他回答说,应该压缩服务器端,而不是使用webpack。然而,为什么会有压缩插件呢

设置为Vue、Webpack(单页应用程序)、nginx、Django、Docker

以下是我当前的网页包配置:

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

const env = process.env.NODE_ENV === 'testing'
    ? require('../config/test.env')
    : require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
    mode: 'production',
    module: {
        rules: utils.styleLoaders({
            sourceMap: config.build.productionSourceMap,
            extract: true,
            usePostCSS: true
        })
    },
    devtool: config.build.productionSourceMap ? config.build.devtool : false,
    output: {
        path: config.build.assetsRoot,
        filename: utils.assetsPath('js/[name].[chunkhash].js'),
        chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    },
    plugins: [
        // extract css into its own file
        new MiniCssExtractPlugin({
            filename: utils.assetsPath('css/[name].[hash:7].css'),
            chunkFilename: utils.assetsPath('css/[id].[hash:7].css')
        }),
        // Compress extracted CSS. We are using this plugin so that possible
        // duplicated CSS from different components can be deduped.
        new OptimizeCSSPlugin({
            cssProcessorOptions: config.build.productionSourceMap
            ? { safe: true, map: { inline: false } }
            : { safe: true }
        }),
        // generate dist index.html with correct asset hash for caching.
        // you can customize output by editing /index.html
        // see https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
            filename: process.env.NODE_ENV === 'testing'
                ? 'index.html'
                : config.build.index,
            template: 'index.html',
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
                // more options:
                // https://github.com/kangax/html-minifier#options-quick-reference
            },
            // necessary to consistently work with multiple chunks via CommonsChunkPlugin
            chunksSortMode: 'dependency',
            jsExtension: '.gz'
        }),
        // keep module.id stable when vender modules does not change
        new webpack.HashedModuleIdsPlugin(),
        // copy custom static assets
        new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, '../static'),
                to: config.build.assetsSubDirectory,
                ignore: ['.*']
            }
        ]),
    ],
    optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            chunks: 'all',
            maxInitialRequests: Infinity,
            minSize: 0,
            cacheGroups: {
                default: false,
                vendors: false,
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    chunks: 'all',
                    priority: 20,
                    name(module) {
                        // get the name. E.g. node_modules/packageName/not/this/part.js
                        // or node_modules/packageName
                        const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

                        // npm package names are URL-safe, but some servers don't like @ symbols
                        return `npm.${packageName.replace('@', '')}`;
                    },
                },
                common: {
                    name: 'common',
                    minChunks: 2,
                    chunks: 'async',
                    priority: 10,
                    reuseExistingChunk: true,
                    enforce: true
                },
            },
        },
    },
})

if (config.build.productionGzip) {
    const CompressionWebpackPlugin = require('compression-webpack-plugin')

    webpackConfig.plugins.push(
        new CompressionWebpackPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.(js|css)(\?.*)?$/i,
            //threshold: 10240,
            //minRatio: 0.8,
            deleteOriginalAssets: true,
        }),
    )
}

if (config.build.bundleAnalyzerReport) {
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
    webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

关于压缩插件为什么存在的具体问题,答案是它在服务器端创建压缩包

JavaScript的请求是通过带有纯JS扩展的客户端浏览器发出的。但是,在浏览器请求中发送的头包括它可以接受的响应类型。查看
accept encoding
字段,通常会在那里看到gzip和Brotli

您的服务器应该接收JS文件的请求,但是那里的代码应该在头中查找,以确定作为响应的格式。您的服务器通常应该返回以前使用压缩插件压缩的内容,客户端可以处理这些内容