nodeexpressServer不提供带有brotli和gzip压缩的压缩静态文件



我有一个使用react可加载SSR插件npm包实现SSR的react应用程序。

我遵循本教程Brotli压缩的故事来实现Brotli和gzip压缩

我可以在构建文件夹中看到.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, paths.publicPath), {
enableBrotli: true,
orderPreference: ['br', 'gz'],
setHeaders(res) {
res.setHeader('Content-Encoding', 'br');
res.setHeader('Cache-Control', 'public, max-age=31536000');
},
})
);
server.use(compression());

start.js

//app.use('/static',express.static(paths.clientBuild((;

在start.js.中评论了上面的代码

在浏览器中,我看到了与以前相同大小的静态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静态gzip不起作用。

仅供参考:我的构建文件夹位于根目录上,具有以下结构:

构建/客户端/静态/

我认为这个问题和您提供expressStaticGzip 的路径有关

下面是一个教程,它为您提供了有关目录结构和设置的更多详细信息。https://codeburst.io/express-brotli-webpack-a60773e7ec6c

expressStaticGzip(path.join(__dirname)

最新更新