码迷,mamicode.com
首页 > 其他好文 > 详细

[Vue CLI 3] 配置解析之 indexPath

时间:2018-12-18 19:43:23      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:包含   one   ons   案例   proc   app   pac   service   code   

vue.config.js 配置中有一个 indexPath 的配置,我们先看看它有什么用?

用来指定 index.html 最终生成的路径(相对于 outputDir)

先看看它的默认值:在文件 @vue/cli-service/lib/options.js


indexPath: joi.string()

默认值:


indexPath: ‘index.html‘

使用案例:

我们在 vue.config.js 中配置:


indexPath: ‘1/2/3/b.html‘

最终在编译之后的目录 dist(默认)下面会生成:

1/2/3/b.html 的文件,内部不会发生变化

我们看一下背后的实现:@vue/cli-service/lib/config/app.js 文件中

两层判断:

1、先判断是不会 product 环境


const isProd = process.env.NODE_ENV === ‘production‘
if (isProd) {}

2、是否配置了 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 下的插件是如何编写的:

1、它是 class 的方式:

内部包含了 constructor 和 apply(参数是 compiler)


module.exports = class MovePlugin {
  constructor () {}
  apply (compiler) {}
}

2、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 })
}

3、apply 内部的结构呢


compiler.hooks.done.tap(‘move-plugin‘, () => {
    // ...
})

通过 compiler tap 来注册插件,这里的 done 是一个生命周期的钩子函数:编译完成


compiler.hooks.someHook.tap()

这里还有其他钩子:

  • run
  • beforeRun
  • compile
  • beforeCompile
  • afterCompile
  • emit
  • afterEmit

来源:https://segmentfault.com/a/1190000016267660

[Vue CLI 3] 配置解析之 indexPath

标签:包含   one   ons   案例   proc   app   pac   service   code   

原文地址:https://www.cnblogs.com/lovellll/p/10138785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!