我们看一下官网给的 multi-page 的配置:需要在 vue.config.js 配置 pages,示例如下:
pages: {
index: { // page 的入口
entry: 'src/index/main.js', // 模板来源
template: 'public/index.html', // 在 dist/index.html 的输出
filename: 'index.html', // 当使用 title 选项时,
// template 中的 title 标签需要是 <%= htmlWebpackPlugin.options.title %>
title: 'Index Page', // 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ['chunk-vendors', 'chunk-common', 'index']
}, // 当使用只有入口的字符串格式时,
// 模板会被推导为 `public/subpage.html`
// 并且如果找不到的话,就回退到 `public/index.html`。
// 输出文件名会被推导为 `subpage.html`。
subpage: 'src/subpage/main.js'
}每一个页面中就是一个对象,包含了如下配置:
entry 入口文件的路径
template 模板文件的路径
filename 编译之后的 html 文件名
title html 中的 title
chunks 打包的 chunk 文件,数组格式,包含入口文件
首先,我们需要设计一下 src 目录下面放置 multi-page 的文件:
看了很多多页项目,有 2 个方案:
一种叫 pages 文件夹
一种叫 views 或者其他名字的文件夹
大家自行选择或者定义就好了,这里我们选 pages
我们再看一下里面的文件:
入口文件:文件名可以叫 main.js 或者 index.js
模板文件:可以用统一的 'public/index.html',或者目录内放置一个自己的,取名 index.html
title:可以从一个文件里面取
src pages page1 index.html main.js App.vue page2 index.html main.js App.vue
下面就是通过函数来生成 pages 的配置:
第一步:找到入口文件
可以用 glob
const glob = require('glob')pages 目录的位置,可以用相对路径,也可以用绝对路径:
const path = require('path')const PAGES_PATH = path.resolve(__dirname, './src/pages')定义一个 pages 对象:
const pages = {}glob.sync(PAGES_PATH + 'public/index.htmlconst htmlPath = api.resolve('public/index.html')defaultHtmlPath 路径是:
/Usersnode_modules/@vue/cli-service/lib/config/index-default.html
const defaultHtmlPath = path.resolve(__dirname, 'index-default.html')如果:
1、用户自定义的模板存在就直接给 templatePath
2、如果不存在,先取 public/index.html,再不行就取 node_modules 里面的const templatePath = hasDedicatedTemplate ? template : fs.existsSync(htmlPath) ? htmlPath : defaultHtmlPath最终通过 html-webpack-plugin 插件来生成指定名字的 html 文件到指定目录:
1、指定目录:
由 vue.config.js 中的 outputDir 来决定
const outputDir = api.resolve(options.outputDir)2、生成 webpack config 关于 html-webpack-plugin 的部分:
const HTMLPlugin = require('html-webpack-plugin') webpackConfig .plugin(`html-${name}`) .use(HTMLPlugin, [pageHtmlOptions])pageHtmlOptions 的处理细节:
传递给 html-webpack-plugin 插件的参数,这里默认会设置 chunks 的,所以上面实战中配置也是无用功
const pageHtmlOptions = Object.assign({}, htmlOptions, { chunks: chunks || ['chunk-vendors', 'chunk-common', name], template: templatePath, filename: ensureRelative(outputDir, filename), title })
作者:dailyvuejs
链接:https://www.jianshu.com/p/548c7fc29e5f


![[Vue CLI 3] 多页应用实践和源码设计 [Vue CLI 3] 多页应用实践和源码设计](http://www.mshxw.com/aiimages/31/241291.png)
