我正在使用webpack捆绑进行React项目。我想减小包的大小,因此决定使用压缩插件来提供gzip文件,以获取较小的包大小。该项目构建良好,我得到了一个不错的小包装,但是这是我的问题..当我为当前的项目提供服务时,这是我得到的错误:
看着我意识到,由于某种原因,它不是返回main.js或vendor.js的内容,而是返回我的index.html文件
我相当确定我的apache服务器已配置为处理gzip编码,因为我可以在响应标头中看到它:
这是我正在使用的webpack配置:
const appConstants = function() {
switch (process.env.NODE_ENV) {
case 'local':
const localConfig = require('./config/local');
return localConfig.config();
case 'development':
const devConfig = require('./config/development');
return devConfig.config();
case 'production':
default:
const prodConfig = require('./config/production');
return prodConfig.config();
}
};
const HtmlWebPackPlugin = require("html-webpack-plugin");
const webpack = require('webpack');
const CompressionPlugin = require('compression-webpack-plugin');
const htmlWebpackPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
hash: true
});
const compressionPlugin = new CompressionPlugin({
filename: "[path].gz[query]",
test: /\.(js|css)$/,
algorithm: 'gzip',
deleteOriginalAssets: true
});
let webpackConfig = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
exclude: [ /assets/, /node_modules/ ],
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
localIdentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true
}
}
]
},
{
test: /\.(pdf|jpg|png|gif|svg|ico)$/,
exclude: [/node_modules/],
use: [
{
loader: 'file-loader'
},
]
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
exclude: [/node_modules/],
use: {
loader: 'url-loader?limit100000'
}
}
]
},
entry: [ "@babel/polyfill", "./src/index.js"],
output: {
publicPath: appConstants().DS_BASENAME ? JSON.parse(appConstants().DS_BASENAME) : '/',
chunkFilename: '[name].[chunkhash].js'
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
plugins: [
htmlWebpackPlugin,
compressionPlugin,
new webpack.DefinePlugin({
'process.env': appConstants()
}),
new webpack.EnvironmentPlugin(['NODE_ENV']),
],
devServer: {
historyApiFallback: true
}
};
// configure source map per-env
if (process.env.NODE_ENV === 'local') {
webpackConfig.devtool = 'source-map';
} else {
webpackConfig.devtool = 'hidden-source-map';
}
module.exports = webpackConfig;
我无法弄清楚为什么浏览器无法读取/识别gzip。我已经尝试了几篇类似的问题,但没有解决方案。
答案 0 :(得分:0)
您需要添加中间件功能来处理后缀为.gz的.js和.css文件 这样
const app = express()
app.get('*.js', function(req, res, next) {
req.url = req.url + '.gz'
res.set('Content-Encoding', 'gzip')
res.set('Content-Type', 'text/javascript')
next()
})
app.get('*.css', function(req, res, next) {
req.url = req.url + '.gz'
res.set('Content-Encoding', 'gzip')
res.set('Content-Type', 'text/css')
next()
})
app.use('/dist', serve('./dist', true))
app.use(express.static('./dist'));
您必须在express.static之前添加中间件功能
祝你好运!