我有一个React应用程序,通过ExpressJS提供。我已将Webpack配置为创建.gz
资产。
但是HtmlWebpackPlugin在我的index.html中创建了一个.js
文件包。
我认为这是因为在我的output
中的webpack.prod.js
道具中,我的文件名为.js
{/ p>}。
如何配置此功能以在支持时返回.gz
扩展名?
Express App
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.resolve(__dirname, '../dist')));
app.get('*.js', function(req, res, next) {
req.url = req.url + '.gz';
res.set('Content-Encoding', 'gzip');
next();
});
app.get('/healthz', (req, res) => res.send('OK'));
app.get('*', (req, res) =>
res.sendFile(path.resolve(__dirname, '../dist/index.html'))
);
const PORT = process.env.SERVER_PORT || 3000;
const HOST = process.env.SERVER_HOST || '127.0.0.1';
app.listen(PORT);
console.log(`API started on ${HOST}:${PORT}`);
webpack.common.js
const commonPaths = require('../common-paths');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
context: commonPaths.appPath,
entry: './index.jsx',
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{ test: /\.(jsx?)$/, exclude: /node_modules/, use: ['babel-loader'] }
]
},
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
chunks: 'initial',
test: 'vendor',
name: 'vendor',
enforce: true
}
}
}
},
plugins: [
new CompressionPlugin({
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new HtmlWebpackPlugin({
title: 'Web App',
template: commonPaths.projectRoot + '/public/index.html',
inject: 'body'
})
]
};
webpack.prod.js
const commonPaths = require('../common-paths');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
devtool: 'source-map',
mode: 'production',
output: {
filename: 'static/[name].[hash].min.js',
path: commonPaths.outputPath
},
plugins: [
new ExtractTextPlugin({
filename: 'static/styles.[hash].min.css',
allChunks: true
})
]
};
我还在我的Express App中尝试了以下内容,因为它无法提供文件...
const express = require('express');
const path = require('path');
const app = express();
app.use(
express.static(path.resolve(__dirname, '../dist'), {
index: false,
fallthrough: true,
setHeaders: (res) => {
res.set('Content-Encoding', 'gzip');
}
})
);
app.get('/healthz', (req, res) => res.send('OK'));
app.get('*', (req, res) =>
res.sendFile(path.resolve(__dirname, '../dist/index.html'))
);
const PORT = process.env.SERVER_PORT || 3000;
const HOST = process.env.SERVER_HOST || '127.0.0.1';
app.listen(PORT);
console.log(`API started on ${HOST}:${PORT}`);