本文介绍如何利用 html-webpack-plugin 动态修改 Vue 项目页面的 title。针对 vue-cli2.X 和 vue-cli3.X 分别提供了在 config/index.js 或 vue.config.js 中配置 title 并注入到 index.html 的方法,同时讲解了如何在 main.js 中全局获取 title 并在组件中使用,实现一处修改多处生效。
vue-cli2.X 配置方法
在 vue-cli2.X 项目中,首先需要修改 config 目录下的 index.js 文件。
const title = '标题1'
// const title = '标题2'
// const title = '标题3'
module.exports = {
title: title,
dev: { ... },
build: { ... },
test: { ... }
接着,在 webpack.dev.conf.js 和 webpack.prod.conf.js 文件中配置 HtmlWebpackPlugin 时,可以使用 config.title。
new HtmlWebpackPlugin({
title: config.title,
...
}),
最后,在 index.html 文件中通过 <%= htmlWebpackPlugin.options.title %> 使用。
<title><%= htmlWebpackPlugin.options.title %></title>
如果项目需要根据 title 有不同的布局,可以在 main.js 中引入 config 并设置为全局变量。
const config = require('../config/index')
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
data () {
return {
title: config.title
}
}
})
在 vue 文件中通过 $root.title 使用即可,这样打包的时候只要切换 config 目录下的 index 一处地方就好了,不必多处修改降低出错概率。
vue-cli3.X 配置方法
vue-cli3.X:很简单,只要 vue.config.js 中配置。
configureWebpack: config => {
return {
title: title,
resolve: {
alias: {
'@': resolve('src')
}
},
plugins: []
}
}
}
public 目录下的 index.html 使用。
<title><%= webpackConfig.title %></title>
到此这篇关于 html-webpack-plugin 修改页面的 title 的方法的文章就介绍到这了,更多相关 html-webpack-plugin 修改页面的 title 内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!