Vue-Cli: htmlWebpackPlugin的'title'选项无效。

35

我正在使用vue-cli (3.4.1),尝试简单地更改文档的标题。

我在vue.config.js中添加了以下内容。

    chainWebpack: (config) => {
        config
          .plugin('html')
          .tap((args) => {
            args[0].title = 'Custom Title';
            return args;
          });
      },

并使用vue inspect --plugin html检查了webpack配置,结果如下:

Translated Text:

And inspected the webpack configuration with vue inspect --plugin html, resulting in the following output:

    /* config.plugin('html') */
    new HtmlWebpackPlugin(
      {
        templateParameters: function () { /* omitted long function */ },
        template: '<path>\node_modules\\@vue\\cli-service\\lib\\config\\index-default.html',
        title: 'Custom Title'
      }
    )

Web应用程序的标题仍然显示为“Vue App”。

有任何想法为什么?

PS:我不希望在应用程序中的某个地方设置document.title ='Custom Title'。 我希望在构建时更改文档的元素中标签之间的标题。</p>


1
可能是一个 bug。我建议报告它 - tony19
6个回答

59

很遗憾以上的回答没有帮助到我。

官方文档所述,您只需要将vue.config.js添加到根文件夹中并添加以下内容:

    // vue.config.js
    module.exports = {
      chainWebpack: config => {
        config
        .plugin('html')
        .tap(args => {
          args[0].title = 'Your new title'
          return args
        })
      }
    }

记住,您需要停止应用程序,并使用npm run serve重新启动。这对我有效。


34
根据Vue CLI的配置参考文档,您可以通过覆盖vue.config.js中的页面部分来设置标题。由于除了entry之外,所有配置选项都是可选的,因此这应该就可以了。
module.exports = {
  pages: {
    index: {
      entry: 'src/index/main.js',
      title: 'Custom Title'
    }
  }
}

2
这个对我来说完美地工作了!我只需要修改entry路径以符合我的入口文件设置即可。 - junerockwell
这对我也很有效。我只需要重新启动我的Docker容器即可。 - Pierre de LESPINAY
这是实现所需结果的最简单方法。 - Aymeric Bouzy aybbyk

16
要设置一个 vue-cli 应用程序的标题,你可以在 HtmlWebpackPlugin 中设置标题(就像你已经做的一样)。
/* vue.config.js */
chainWebpack: (config) => {
    config
      .plugin('html')
      .tap((args) => {
        args[0].title = 'Custom Title';
        return args;
      });
  },

那么您必须编辑 public/index.html 中的 <title>,以使用 lodash 语法引用标题。

<!-- public/index.html -->
<head>
  <title><%= htmlWebpackPlugin.options.title %></title>
</head>

请查看Html Webpack Plugin的文档,了解如何编写自己的模板!

希望这可以帮助你!


3

我按照@tony19的建议提交了一个错误报告。

tldnr: 编辑public/index.html模板中的标题,该模板将在构建时使用。

长版本:我的项目中不再有public/index.html,显然我在一段时间前删除了它,因此从未使用过模板功能。cli仍然使用某个位置的模板,因此对于htmlWebpackPlugin的所有更改都无效。

因此,您可以禁用index.html-template并修改htmlWebpackPlugin,或者您可以编辑模板以进行更改。


2
我无法使webpack-config中的标题更改生效,我猜测vue-cli后来覆盖了它。对我有效的方法是在.env文件中设置VUE_APP_TITLE=<自定义标题>,并在index.html中使用<title><%= process.env.VUE_APP_TITLE %></title>。请参考来源

0

您可以通过在 vue-cli 应用程序的 package.json 根目录中设置 "name" 属性来设置 HtmlWebpackPlugin 使用的标题。无需使用 chainWebpack 来更改标题。


5
这确实有效,但是 package.json 的名称只能使用 小写字母、连字符和下划线 - sifriday

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