我使用 react 和 webpack 来构建 bundle.js 文件,我使用 'html-webpack-plugin' 插件,因为我需要将版本添加到 bundle.js 文件名以防止部署后缓存,我遇到了一个问题,你可以看这里:
https://imgur.com/a/yM1NI8n
我的 webpack 配置:
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
var path = require('path');
var CleanWebpackPluginConfig = new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: ['**/*.js', '!static-files*'],
verbose: true
});
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template : __dirname + '/dist/index.html',
filename : 'index.html',
inject : 'body'
});
module.exports = {
entry: ['babel-polyfill', './src/index.web.js'],
target: 'web',
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(jpe?g|png|gif|svg|woff|eot|ttf)$/i,
use: [
'url-loader?limit=10000',
'img-loader'
]
}
]
},
plugins: [
CleanWebpackPluginConfig,
HtmlWebpackPluginConfig
],
resolve: {
extensions: ['.web.js', '.js']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.[contenthash].js',
chunkFilename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: './dist',
hot: false,
port: process.env.PORT || 9514,
historyApiFallback: true
}
};
我的问题是:是否有可能在 index.html 中自动更新 bundle.js 文件名?
最佳答案
找到了解决方法:
首先,我必须创建不包含 bundle.js 的 index-template.html 文件,然后我必须在此处更新配置:
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template : __dirname + '/dist/template-index.html',
filename : 'index.html',
inject : 'body'
});
并删除我的 index.html。
所以每次都会根据模板文件创建新的 index.html 并在新的 index.html 中添加 script 标签。
关于reactjs - Webpack 'html-webpack-plugin' 在每次构建后添加额外的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55632394/