【发布时间】:2023-07-16 13:37:01
【问题描述】:
我的服务器不向客户端提供 GZIPd JavaScript 文件。
我有一个简单的 Vue.js 应用程序,托管在 Heroku 上。当我通过控制台中的“npm run build”构建站点时,它会为 /dist/js 目录填充每个 JavaScript 文件的 4 个文件,正如我所期望的那样。
例如:
chunk-vendors.e26db277.js
chunk-vendors.e26db277.js.gz
chunk-vendors.e26db277.js.map
chunk-vendors.e26db277.js.map.gz
为了启用压缩,我使用以下命令安装了 webpack:
npm install --save-dev compression-webpack-plugin
然后我将 vue.config.js 设置为以下内容:
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
chainWebpack(config) {
config.plugins.delete('prefetch');
config.plugin('CompressionPlugin').use(CompressionPlugin);
}
};
基本上我遵循了这个教程: https://medium.com/@aetherus.zhou/vue-cli-3-performance-optimization-55316dcd491c
当我在浏览器中检查 HTTP 请求时,它说它接受 gzip:
Accept-Encoding: gzip, deflate, br
我卡住的地方是,让服务器实际交付 .gz 文件。
在教程中它说“这样一个静态网站的服务器块看起来像这样:
server {
listen 80;
server_name www.example.io;
root /path/to/the/directory;
index index.html;
gzip_static on;
location /index.html {
etag on;
}
location / {
etag off;
add_header Cache-Control max-age=315360000, immutable;
}
}
但是我在哪里可以找到这个块?
这是我的 server.js:
const express = require('express')
const serveStatic = require('serve-static')
const path = require('path')
const app = express()
//here we are configuring dist to serve app files
app.use('/', serveStatic(path.join(__dirname, '/dist')))
// this * route is to serve project on different page routes except root `/`
app.get(/.*/, function (req, res) {
res.sendFile(path.join(__dirname, '/dist/index.html'))
})
const port = process.env.PORT || 8080;
app.listen(port);
【问题讨论】:
标签: javascript node.js vue.js webpack gzip