压缩webpack插件

时间:2018-05-21 04:32:13

标签: javascript webpack compression

我试图弄清楚如何正确使用 webpack-html-plugin 压缩插件,后者的文档有点稀缺。< / p>

我的webpack配置声明:

output: {
  filename: 'js/[name]-[hash].js',

压缩插件最后运行

new CompressionPlugin({
    asset: "[path].gz[query]",
    algorithm: "gzip"
})

最后,脚本被正确生成和压缩。

js/app-caf3b4b3.js.gz     382 kB          [emitted]  [big] 

我可以在index.html模板

中声明gzip压缩文件的预加载
 <link rel="preload" href="<%= htmlWebpackPlugin.files.chunks[chunk].entry %>.gz" as="script">

但是webpack负责插入这一行:

<script type="text/javascript" src="/js/app-caf3b4b3.js">

<body></body>

如何让webpack使用压缩脚本?

2 个答案:

答案 0 :(得分:3)

您不需要在html中链接压缩文件。你必须做这个服务器端。你也可以gzip css和html文件。

将服务器设置为使用gzip压缩发送文件,您还需要正确的标头来告诉浏览器如何解释该压缩文件。

如果您使用的是Apache服务器,则可以使用 .htaccess 文件启用gzip压缩。

我将它用于我的Apache服务器:

# enable the rewrite capabilities
RewriteEngine On

# prevents the rule from being overrided by .htaccess files in subdirectories
RewriteOptions InheritDownBefore

# provide a URL-path base (not a file-path base) for any relative paths in the rule's target
RewriteBase /

# GZIP
## allows you to have certain browsers uncompress information on the fly
AddEncoding gzip .gz
## serve gzip .css files if they exist and the client accepts gzip
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.css $1\.css\.gz [QSA]
## serve gzip .js files if they exist and the client accepts gzip
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.js $1\.js\.gz [QSA]
## serve gzip .html files if they exist and the client accepts gzip
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.html $1\.html\.gz [QSA]
## serve correct content types, and prevent mod_deflate double gzip
RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1,E=is_gzip:1]
RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1,E=is_gzip:1]
RewriteRule \.html\.gz$ - [T=text/html,E=no-gzip:1,E=is_gzip:1]
Header set Content-Encoding "gzip" env=is_gzip

您可以在Google上获取有关如何使用gzip压缩优化网站的更多信息

https://gtmetrix.com/enable-gzip-compression.html

https://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/

https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer#text_compression_with_gzip

答案 1 :(得分:0)

您可以通过Webpack Compression Plugin从您的Vue.js应用或服务器端执行此操作。我将回答Vue应用程序配置。

步骤:

  1. 创建vue.config.js文件(如果尚不存在)
  2. 根据这些内容添加内容

    const CompressionWebpackPlugin = require("compression-webpack-plugin");
    
    module.exports = {
    
      configureWebpack: {
    
        plugins: [
          new CompressionWebpackPlugin({
            filename: "[path].gz[query]",
            algorithm: "gzip",
            test: /\.(js|css)$/,
           ...
    
          })
        ]
      }
    };
    

插件文档中提供了更多选项。