
vue cli 中引入公共模板
vue cli 创建的项目中,在页面中引入公共 HTML 代码的方法是模板模块化。
步骤:
1. 安装 html-webpack-plugin
npm install --save-dev html-webpack-plugin
2. 配置 vue.config.js
立即学习“前端免费学习笔记(深入)”;
在 vue.config.js 中配置 html-webpack-plugin:
const fs = require('fs')
const header = fs.readFileSync('./public/header.html').toString()
module.exports = {
chainWebpack: (config) => {
config.plugin('html').tap((args) => {
args[0].header = header
return args
})
}
}3. 创建公共模板文件
在 public 目录下创建包含要引入的 HTML 代码的文件,如 header.html:
4. 在 index.html 中引用公共模板
在 public/index.html 中引用公共模板:
<%= htmlWebpackPlugin.options.header %>
5. 运行项目
运行 npm run serve 启动项目。此时,公共模板中的 HTML 代码将被引入到所有页面中。











