问题描述
我已经使用react loadable SSR addon npm package对应用程序进行了SSR实施。
我正在按照本教程A Tale of Brotli Compression来实现brotli和gzip压缩
我可以在build文件夹中看到.br和.gzip压缩文件。但是当我在localhost上检查时这些文件不起作用,我不确定是否是因为我在localhost开发服务器或其他地方检查。
遵循以下步骤:
webpackConfig / plugins.js
const CompressionPlugin = require('compression-webpack-plugin');
const brotliPlugin = require('brotli-webpack-plugin');
new CompressionPlugin({
filename: '[path].gz[query]',}),new brotliPlugin({
asset: '[path].br[query]',test: /\.(js|css|html|svg)$/,threshold: 10240,minRatio: 0.8,
server / index.js
import expressstaticGzip from 'express-static-gzip';
import path from 'path';
const server = express();
server.use(cors());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(cookieParser());
server.use(
'/static*',// '/build/client',expressstaticGzip(path.join(paths.clientBuild,paths.publicPath),{
enablebrotli: true,orderPreference: ['br','gz'],setHeaders(res) {
res.setHeader('content-encoding','br');
res.setHeader('Cache-Control','public,max-age=31536000');
},})
);
server.use(
'/static*',expressstaticGzip(path.join(paths.serverBuild,})
);
server.use(compression());
start.js
// app.use('/ static',express.static(paths.clientBuild));
在浏览器中,我看到的静态JS和CSS文件大小与以前相同。
更新:
尝试了几件事之后,我了解到我需要在start.js中进行更改,而不是server / index.js
因此,为了测试事情是否按预期进行,我添加了一个中间件来测试特定的用例:
app.get('/static*',function (req,res,next) {
console.log('req buncle url',req.url)
req.url = req.url + '.gz';
res.set('content-encoding','gzip');
res.set('Content-Type','text/javascript');
next();
});
以上代码按预期工作,我在浏览器中压缩了bundle.js文件。但是express-static-gzip不能使用。
仅供参考:我的构建文件夹位于根目录上,结构如下:
内部版本/客户端/静态/
解决方法
我认为问题与您提供的expressStaticGzip路径有关
这里是一个教程,为您提供有关目录结构和设置的更多详细信息。 https://codeburst.io/express-brotli-webpack-a60773e7ec6c
expressStaticGzip(path.join(__dirname)