在 vue.config.js
配置中有一个 indexPath
的配置,咱们先看看它有什么用?html
用来
指定 index.html 最终生成的路径
(相对于 outputDir)
先看看它的默认值:在文件 @vue/cli-service/lib/options.js
中vue
indexPath: joi.string()
默认值:webpack
indexPath: 'index.html'
使用案例:web
咱们在 vue.config.js 中配置:app
indexPath: '1/2/3/b.html'
最终在编译以后的目录 dist(默认)下面会生成:函数
1/2/3/b.html 的文件,内部不会发生变化工具
咱们看一下背后的实现:@vue/cli-service/lib/config/app.js 文件中ui
两层判断:this
一、先判断是不会 product 环境插件
const isProd = process.env.NODE_ENV === 'production' if (isProd) {}
二、是否配置了 indexPath
if (options.indexPath !== 'index.html') { }
经过内置的插件去修改路径,插件文件在 cli-service/lib/webpack/MovePlugin.js
webpackConfig .plugin('move-index') .use(require('../webpack/MovePlugin'), [ path.resolve(outputDir, 'index.html'), path.resolve(outputDir, options.indexPath) ])
这个对应的配置,默认的编译以后的目录是 dist,传入了 2 个路径:
/* config.plugin('move-index') */ new MovePlugin( '/Users/***/dist/index.html', '/Users/***/dist/1/2/3/b.html' )
咱们看一下 webpack 4 下的插件是如何编写的:
一、它是 class 的方式:
内部包含了 constructor 和 apply(参数是 compiler)
module.exports = class MovePlugin { constructor () {} apply (compiler) {} }
二、constructor 里面其实要处理传入的参数:
constructor (from, to) { this.from = from this.to = to }
定义了一个 from,一个 to,而后其实就是把 from 经过 fs 的 moveSync 函数移动到 to 里面:
这里咱们依赖了工具包:fs-extra
const fs = require('fs-extra')
具体流程以下:先判断 from 的路径是否存在
if (fs.existsSync(this.from)) { fs.moveSync(this.from, this.to, { overwrite: true }) }
三、apply 内部的结构呢
compiler.hooks.done.tap('move-plugin', () => { // ... })
经过 compiler tap 来注册插件,这里的 done 是一个生命周期的钩子函数:编译完成
compiler.hooks.someHook.tap()
这里还有其余钩子: