html-webpack-plugin:如何将参数(例如标题)注入模板?

14

我正在尝试将标题传递给html-webpack-plugin,但它根本不创建标题标签 :(

有人可以告诉我问题出在哪里吗?

webpack.js

var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');

module.exports = {
    entry: ['./src/app/main.ts'],
    output: {
        filename: 'build.js',
        path: 'dist'
    },
    resolve: {
        root: __dirname,
        extensions: ['', '.ts', '.js', '.json']
    },
    resolveLoader: {
        modulesDirectories: ["node_modules"]
    },
    devtool: "source-map",
    plugins: [
        new HtmlWebpackPlugin({
            title : 'Hello',
            template: './src/index.html',
            inject: 'body',
            hash: true,
        })
    ],
    module: {
        loaders: loaders
    }
};

这里是index.html

<!doctype html>
<html lang="en">
<head>
    <noscript>
        <meta http-equiv="refresh" content="0; url=https://en.wikipedia.org/wiki/JavaScript">
    </noscript>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
    <ui-view></ui-view>
</body>
</html>

当我启动Webpack服务器时,标题没有被注入?

5个回答

11

在你的html文件中尝试使用以下代码<title><%= htmlWebpackPlugin.options.title %></title>。你可以查看我的存储库webpack-setup中的index.html文件作为参考。


2
你能解释一下这是如何工作的吗?在构建时肯定有某种模板引擎在运行以处理它。 - Andy
@Andy,这基本上是webpack的一个特性,它在内部使用可插拔的钩子。而且,所有围绕webpack开发的插件也都利用了这些钩子。特别是对于html-webpack-plugin,你可以参考这些事件流程:https://github.com/jantimon/html-webpack-plugin#events - Samar Panda

3

这个问题在这里有报告:Title not working. #176

如果您想添加动态的<title>标签,您应该使用模板语言,如ejsjade等。


0
在Webpack中插入此配置。
{
    test: /\.(index.html)$/,
    use: [
      {loader: "file-loader"},
      { loader: "extract-loader" },
      {
      loader: 'html-loader',
      options: {
        attrs: [':data-src']
      }
    }]
  }

确保此配置:

new HtmlWebpackPlugin({
  title: "My Page TItle",
  template: './index.html'
}),

-1

你现在可以像这样使用templateParameters:

new HtmlWebpackPlugin({
  template: 'index.html',
  templateParameters: {
    title: 'My web app',
  },

并在您的index.html文件头部添加:

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

-3
你尝试过在模板HTML文件./src/index.html中注入标题标签吗?
<!doctype html>
<html lang="en">
<head>
    <noscript>
        <meta http-equiv="refresh" content="0; url=https://en.wikipedia.org/wiki/JavaScript">
    </noscript>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <title>Hello</title>
</head>
<body>
    <ui-view></ui-view>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接