javascript - 压缩 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 使用压缩脚本?
解决方案
您不需要在 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/
推荐阅读
- asp.net-mvc - 使用 @Html.CheckBoxFor 禁用多项选择,同时允许框之间有空格 - ASP.Net (Core) MVC
- android - 如何通过 Uri 链接打开 GooglePhoto 的视频/图像?
- javascript - Bootstrap 中的自适应徽标
- android - Flutter Provider (ChangeNotifierProxyProvider) 失败,因为 hasListeners 为 true
- python - 如何在 Tensorflow 2.0 中将占位符从 Tensorflow 1.0 转换为 tf.keras.input
- r - 从动态字符串向量中提取某些单词
- mysql - 在sql查询中添加日期,vb.net
- java - 如何在 Mockito 中对 if/else 语句进行单元测试
- chai - 与属性深度相等的柴抛
- c++ - Arduino - MagStripe card.available 暂停,没有其他代码可以运行