reactjs - Webpack 'html-webpack-plugin' 在每次构建后添加额外的脚本

标签 reactjs webpack

我使用 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/

相关文章:

javascript - TypeError : default. a.createClass 不是 React v16 中的函数

javascript - webpack 路径浏览器 polyfill 失败

reactjs - 在 React 中,为什么 useState(foo()) 在每次重新渲染时调用 foo

javascript - 迁移现有的 RequireJS 应用程序以使用 Webpack

javascript - 通过创建隐藏输入在 React 中复制文本

javascript - 使用 .jsx 扩展名测试 React 组件

javascript - 使用 Electron 伪造打包应用程序时出现问题 "Can' t 解决 './→' “

reactjs - 将 Webpack React 库 bundle 为 ESM 模块 - 在非对象上调用 Object.defineProperty

javascript - 使用 Ag-Grid Enterprise 许可证获取 'ag-grid: Looking for component [agSetColumnFilter] but it wasn' t 找到。”错误

javascript - 等待子组件获取数据,然后渲染