两种方式
- 使用 compression 中间件自动压缩 webpack 打包的 bundle.js
- 直接返回 webpack 压缩好的 bundle.js.gz
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express gzip</title>
</head>
<body>
<script src="/js/bundle.js"></script>
<script src="/js/bundle.js.gz"></script>
</body>
</html>
const express = require('express')
const compression = require('compression')
const path = require('path')
const app = express()
app.use(compression({ filter: shouldCompress }))
function shouldCompress (req, res) {
if (req.path.indexOf('.gz') !== -1) {
res.set('Content-Encoding', 'gzip')
return false
}
return compression.filter(req, res)
}
app.use(express.static('static'))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'static/index.html'))
})
app.listen(3000, () => {
console.log('已启动服务器,端口:3000')
})
结果验证
- bundle.js(使用 express 的 compression 压缩为 gzip)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4f7a76bd56e632f81f4e684d5b9d1280.png)
- bundle.js.gz(使用 webpack 打包压缩过的 gzip)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/77b460e89ce2d6241d301d60442a1829.png)
- 大小对比(压缩率跟实际配置有关)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e410c25375131bee4b423fcd54a5a760.png)