首页 > 解决方案 > 压缩 webpack 插件

问题描述

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

我的 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我可以在模板中声明 gzipped 文件的预加载

 <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 使用压缩脚本?

标签: javascriptwebpackcompression

解决方案


您不需要在 html 中链接压缩文件。您必须在服务器端执行此操作。您还可以压缩 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


推荐阅读