【问题标题】:html-webpack-plugin is not inserting options.titlehtml-webpack-plugin 没有插入 options.title
【发布时间】:2019-04-14 00:08:26
【问题描述】:

我正在尝试通过 webpack 和 html-webpack-plugin 将标题动态注入 html。我正在使用车把模板引擎。但是我没有注入title。这是我的 webpack 配置的样子 -

/*
|----------------------------------------------
| setting up webpack build process for app
| @author: jahid haque 
| @copyright: mysite, 2019
|----------------------------------------------
*/

const SriPlugin = require('webpack-subresource-integrity');
const Webpack = require('webpack');
const Path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const Optim = {
    runtimeChunk: 'single',
    splitChunks: {
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 0,
        cacheGroups: {
            vendor: {
                test: /[\\/]node_modules[\\/]/,
                name(module) {
                    const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
                    return `npm.${packageName.replace('@', '')}`;
                },
            },
        },
    },
};

const Module = {
    rules: [
        {
            test: /\.jsx$/,
            exclude: /node_module/,
            use: {
                loader: 'babel-loader',
            },
        },
        {
            test: /\.handlebars$/,
            exclude: /node_module/,
            use: {
                loader: 'handlebars-loader',
            },
        },
    ],
};


module.exports = [

    {
        entry: {
            home: Path.resolve(__dirname, './src/components/home/home.controller.jsx'),
        },
        output: {
            path: Path.resolve(__dirname, './public'),
            filename: Path.join('./js/[name].[contenthash].js'),
            publicPath: '',
            crossOriginLoading: 'anonymous',
        },
        optimization: Optim,

        module: Module,

        plugins: [
            new HtmlWebpackPlugin({
                inject: true,
                hash: true,
                title: 'home page. know how we work',
                template: './src/index.handlebars',
                filename: Path.resolve(__dirname, './public/index.html'),
            }),
            new Webpack.HashedModuleIdsPlugin(),
            new SriPlugin({
                hashFuncNames: ['sha512', 'sha384'],
                enabled: true,
            }),
            new Webpack.NamedChunksPlugin(),
            new CleanWebpackPlugin({
                cleanOnceBeforeBuildPatterns: ['./public/js/'],
            }),
            new WebpackMd5Hash(),
        ],

    },       

    {
        entry: {
            style: Path.resolve(__dirname, './src/scss/app.scss'),
        },
        output: {
            path: Path.resolve(__dirname, './public/css/'),
        },
        optimization: {
            minimizer: [
                new OptimizeCSSAssetsPlugin({}),
            ],
        },
        plugins: [
            new MiniCssExtractPlugin({
                filename: 'styles.css',
            }),
        ],
        module: {
            rules: [
                {
                    test: /\.s?css$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        'css-loader',
                        'sass-loader',
                    ],
                },
            ],
        },
    },
];

我的 htmlWebpack 插件设置是 -

new HtmlWebpackPlugin({
   inject: true,
   hash: true,
   title: 'welcome to home page',
   template: './src/index.handlebars',
   filename: 'index.html',
 }),

在我的 index.handlebars 文件中,我正在应用这个 -

<!doctype html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Test site | <%= htmlWebpackPlugin.options.title %></title>
        <meta name="description" content="">
        <meta name="keywords" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        {{>partials/head}}
    </head>

    <body class="d-flex flex-column h-100 pt-60">

        {{>partials/nav}}

        <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->

        <main role = 'main' class="flex-shrink-0 min-height-750">
            <div id="welcomeHome"></div>    
        </main>  

        {{>partials/footer}}

    </body>
</html>

这里是package.json

{
  "name": "chefcooks",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "scripts": {
    "start": "webpack-dev-server --mode development --open",
    "dev": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "repository": {
    "type": "git",
    "url": "git+https://hidhaque@bitbucket.org/hidhaque/chefcooks.git"
  },
  "author": "jahid haque",
  "license": "ISC",
  "homepage": "https://bitbucket.org/hidhaque/chefcooks#readme",
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.4.3",
    "@babel/preset-env": "^7.4.3",
    "@babel/preset-es2015": "^7.0.0-beta.53",
    "@babel/preset-react": "^7.0.0",
    "@babel/runtime": "^7.4.3",
    "axios": "^0.18.0",
    "babel-loader": "^8.0.5",
    "babel-plugin-transform-async-to-generator": "^6.24.1",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.26.0",
    "clean-webpack-plugin": "^2.0.1",
    "css-loader": "^2.1.1",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-plugin-import": "^2.16.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-react": "^7.12.4",
    "handlebars": "^4.1.1",
    "handlebars-loader": "^1.7.1",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.6.0",
    "node-sass": "^4.11.0",
    "optimize-css-assets-webpack-plugin": "^5.0.1",
    "platform": "^1.3.5",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-loadable": "^5.5.0",
    "sass-loader": "^7.1.0",
    "uglifyjs-webpack-plugin": "^2.1.2",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.3.1",
    "webpack-md5-hash": "0.0.6",
    "webpack-subresource-integrity": "^1.3.2"
  }
}

但我的index.html 中的标题输出仍然存在 -

<title>Test title | <%- HtmlWebpackPlugin.options.title %></title>

这里是.babelrc -

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": [
        "@babel/plugin-transform-runtime", 
        "@babel/plugin-syntax-dynamic-import",
        "transform-async-to-generator",
        [
            "transform-class-properties", 
            { "spec": true }, 
        ]
    ]
}

可以在这里使用一些帮助。我是新来的。非常感谢。

【问题讨论】:

    标签: webpack handlebars.js html-webpack-plugin


    【解决方案1】:

    我试图重现这个问题,但我不能,我做了这个例子,一切正常: webpack.config.js

    const path = require('path');
    const WebpackHTMLPlugin = require('html-webpack-plugin');
    
    module.exports = {
        mode: 'development',
        output: {
            path: path.join(__dirname, 'dist'),
            filename: 'app.bundle.js'
        },
        module: {
            rules: [
                {
                    test: /\.handlebars/,
                    use: 'handlebars-loader',
                    exclude: /node_modules/
                }
            ]
        },
        plugins: [
            new WebpackHTMLPlugin({
                inject: true,
                hash: true,
                title: 'My custom title!',
                template: './template.hbs'
            })
        ]
    }
    

    车把模板:

    <html>
    <head>
        <meta charset="UTF-8">
        <title>{{ htmlWebpackPlugin.options.title }}</title>
    </head>
    <body>
    
    </body>
    </html>
    

    以防万一我给你看我的package.json

    {
      "name": "webpack-hbs",
      "version": "1.0.0",
      "main": "index.js",
      "license": "MIT",
      "scripts": {
        "dev": "webpack --config webpack.config"
      },
      "devDependencies": {
        "handlebars-loader": "^1.7.1",
        "html-webpack-plugin": "^3.2.0",
        "webpack": "^4.30.0",
        "webpack-cli": "^3.3.0"
      }
    }
    

    查看您的代码,我想知道您正在使用 React,也许您可​​以尝试此代码并讨论输出吗?希望这个答案对您的问题有所启发。干杯,西格弗里德。

    更新

    我已经设法解决了这个问题,您可以看到我对index.handlebars 所做的简单更改。显然正如html-webpack-plugin documentation 中指出的那样,当您使用不同的加载器时,它将禁用ejs fallback loader,我假设因为这个&lt;title&gt;&lt;%= htmlWebpackPlugin.options %&gt;&lt;/title&gt; 在您的情况下不起作用,这就是为什么我更改了要使用的模板Handlebars strings interpolation。我仍然认为这很奇怪,也许我错过了其他东西,但无论如何,这现在正在工作。总是乐于助人,欢呼声sigfried。

    【讨论】:

    • sigfried 嘿伙计,我已经编辑了我的问题并添加了完整的webpack.config.jspackage.jsonindex.handlebars。我认为与您的代码伙伴没有太大区别。你能看看吗?干杯。
    • 当然,没问题
    • @jahid 您是否尝试从&lt;title&gt;Test site | &lt;%= htmlWebpackPlugin.options.title %&gt;&lt;/title&gt; 中删除Test site | ?由于某些原因,我不太明白这给我带来了一些麻烦。其他一切似乎都是正确的,我也可以看到你.babelrc 吗?干杯
    • 嘿伙计,谢谢你的回复。我尝试从标题中删除Test site。没有帮助。在我的问题中添加babelrc。干杯。
    • @jahid Mate,我再次尝试重现错误,现在配置一个简单的 React 应用程序,就像您在示例中所做的那样,并且仍然可以正常工作:(。我会拍最后一枪现在,检查您的 head 部分,这是我的示例中唯一缺少的东西,也许该部分正在以某种神奇的方式覆盖标题,现在,没有更多的想法。干杯,sigfried。
    猜你喜欢
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多