Webpack'html-webpack-plugin'在每次构建后添加其他脚本

时间:2019-04-11 12:20:56

标签: 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文件名?

1 个答案:

答案 0 :(得分:0)

找到了一种解决方法: 首先,我必须创建其中没有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中添加脚本标签。