[Vue CLI 3] 多页应用实践和源码设计

我们看一下官网给的 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 标签需要是 <title><%= htmlWebpackPlugin.options.title %></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 + '/*/main.js').forEach(filepath => {
  // ...
})

这里就是去设置对应几个 key 了,很多项目基本多是通过

/ 分隔符来对字符串进行数组话,然后简单地获取

但是熟悉 node.js path 模块的会如下处理:

const pageName = path.basename(path.dirname(filepath))

往 pages 里面循环设置:

pages[pageName] = {
    entry: filepath,
    filename: `${pageName}.html`,
    chunks: ['chunk-vendors', 'chunk-common', pageName]
  }

关于 template 稍微复杂一点,我们需要做判断,如果存在就用自定义的,如果不存在就用通用的

const templatePath = path.dirname(filepath) + '/index.html'

然后通过 fs.existsSync 会判断自定义文件是否存在:

if (!fs.existsSync(templatePath)) {
    // 入口如果不配置直接使用
    templatePath = 'public/index.html'
  }

当然后面我们分享了源码之后,你就会发现你做了无用功

下面我们看一下源码实现部分:

每个版本的 cli-service 多有微小的改动

cli-service/lib/config/app.js 文件

定义了一个变量 multiPageConfig 获取 vue.config.js 取出来的 pages

const multiPageConfig = options.pages

清空一次 entry

webpackConfig.entryPoints.clear()

通过 Object.keys 获取 keys,然后 forEach 循环

const pages = Object.keys(multiPageConfig)
pages.forEach(name => {
})

循环内部:

先定义要用的变量,从 multiPageConfig[name] 的每一个对象取:

const {
          title,
          entry,
          template = `public/${name}.html`,
          filename = `${name}.html`,
          chunks
        } = normalizePageConfig(multiPageConfig[name])

normalizePageConfig 函数如下:

处理 subpage: ‘src/subpage/main.js’ 的情况

const normalizePageConfig = c => typeof c === 'string' ? { entry: c } : c

设置 entry

webpackConfig.entry(name).add(api.resolve(entry))

hasDedicatedTemplate 是判断

用户传递的多页配置自定义模板路径是否存在:

const fs = require('fs')
const hasDedicatedTemplate = fs.existsSync(api.resolve(template))

templatePath 的处理细节:

htmlPath 路径是:

/Users/
*/public/index.html

const htmlPath = api.resolve('public/index.html')

defaultHtmlPath 路径是:

/Users/
*/node_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://segmentfault.com/a/1190000016206160
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞