34

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

我将以下内容添加到 vue.config.js

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

并检查了 webpack 配置,vue inspect --plugin html得到以下输出

    /* 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'
      }
    )

Webapp 的标题仍然是“Vue App”。

任何想法为什么?

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

4

6 回答 6

58

不幸的是,上述答案对我没有帮助。如官方文档中所述,您只需将其添加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。这对我有用。

于 2020-02-25T20:45:46.943 回答
34

根据Vue CLI 的配置参考,您可以通过覆盖中的 pages 部分来设置标题vue.config.js。由于除了条目之外所有配置选项都是可选的,因此应该这样做:

module.exports = {
  pages: {
    index: {
      entry: 'src/index/main.js',
      title: 'Custom Title'
    }
  }
}
于 2020-04-08T19:58:25.250 回答
15

要设置 vue-cli 应用程序的标题,您可以在 HtmlWebpackPlugin 中设置标题(就像您一样)

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

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

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

查看 Html Webpack Plugin关于编写自己的模板的文档!

希望这可以帮助!

于 2019-10-22T16:47:01.470 回答
3

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

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

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

因此,要么禁用 index.html-template 并修改 htmlWebpackPlugin,要么编辑模板以进行更改。

于 2019-03-06T08:32:10.393 回答
2

我无法从 webpack-config 更改标题,我假设 vue-cli 稍后会覆盖配置中的标题。对我有用的是设置和使用VUE_APP_TITLE=<custom title>in 。来源.env<title><%= process.env.VUE_APP_TITLE %></title>index.html

于 2020-04-09T17:45:09.907 回答
0

您可以通过在 vue-cli 应用程序根目录中的 package.json 中设置“name”属性来设置 HtmlWebpackPlugin 使用的标题。不需要chainWebpack 只是为了改变标题。

于 2020-02-12T15:38:12.357 回答