如何在html标题中使用webpack哈希? 2020-11-13更新初始版本

问题描述

我很喜欢webpack,我的webpack.config.js:

plugins: [
    new HtmlWebpackPlugin({
        hash: true,templateParameters:{title: '[name].[contenthash]' },inject: true,}),],

在我的index.ejs中:

<title><%= title %></title>

但是在我的out / index.html中,标题仅为:

<title>[name].[contenthash]</title>

期望:

 <title>app.7472b25c2ed347463dbc</title>

我该如何解决

解决方法

2020-11-13更新

最终,我发现可以使用全局变量: webpack_hash ,像这样:

    <title><%=  'hash'+__webpack_hash__  %></title>

我们可以直接在index.ejs中使用它,而无需在webpack.config.js中做任何事情

初始版本

webpack.config.js:

plugins: [
        new HtmlWebpackPlugin({
            // 1. title is the parameter,you can use in ejs template
            templateParameters:{
                title: JSON.stringify(someting: 'something'),},}),//2. BUILT_AT is a parameter too. can use it.
        new webpack.DefinePlugin({
            BUILT_AT: webpack.DefinePlugin.runtimeValue(Date.now,"some"),//3. for webpack5,you can use global variable: __webpack_hash__
        //new webpack.ExtendedAPIPlugin()
    ],//4. this is not variable,this is module,so use 'import tt' to use it.
    externals: { 
        'ex_title': JSON.stringify({
            tt: 'eitentitle',})
    },