1 新建 vue.config.js
要配置多页面,需要在项目的根目录中新建配置文件 vue.config.js
vue.config.js 是一个可选的配置文件,如果项目的根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。
参考:Vue CLI 配置参考 - vue.config.js
2 使用 page 字段
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/index/main.js',
// 模板来源
template: 'public/index.html',
// 在 dist/index.html 的输出
filename: 'index.html',
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: 'Index Page',
},
}
}
3 如果某一个页面需要引入外部资源,而其他页面不需要这个资源,怎么办?
3.1 简单情况:写多个模版
项目中要用到某富文本插件 editor ,但是它没有npm包,只能在模版页面中用 <script>
直接引用。
项目是多页面 page1 page2 page3:
- page1 会用到 editor ,所以要在模版中引入 插件。
- page2 和 page3 不需要富文本功能,所以在模版中不能 引入 editor插件 。因为这个插件体积很大,会拖累页面加载速度。
这种情况简单,直接写两个模版:一个引用 editor ,一个不引用,解决问题!
3.2 复杂情况:用变量控制
插件 a b c d 都需要在模版页面中引入。page1用a,page2要用b,page3用a c,page4用a b d
情况都不同,要为每个页面出一个模版,太麻烦了吧!
在 pages 中使用 变量 ,配合 ejs语法 ,只使用一个模版搞定:
vue.config.js 中的 pages:
pages: {
page1: {
entry: 'src/page1/main.js',
template: 'public/index.html',
filename: 'page1.html',
// 在模版页面中,title importPluginA importPluginB 都在 htmlWebpackPlugin.options 下能取到
title: '页面1的标题',
importPluginA: false,
importPluginB: true,
},
page2: {
entry: 'src/page2/main.js',
template: 'public/index.html',
filename: 'page2.html',
title: '页面2的标题',
importPluginA: true,
importPluginB: false
},
},
模版 public/index.html
,使用 ejs
语法:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- pluginA -->
<% if (htmlWebpackPlugin.options.importPluginA) { %>
<%= '<script src="./pluginA.js"></script>' %>
<% } %>
<!-- pluginB -->
<% if (htmlWebpackPlugin.options.importPluginB) { %>
<%= '<script src="./pluginB.js"></script>' %>
<% } %>
<!-- 标题 -->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="app"></div>
</body>
</html>