zoukankan      html  css  js  c++  java
  • [Vue CLI 3] 配置解析之 indexPath

    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

  • 相关阅读:
    9月7日总结
    Arbitrage题解
    杀蚂蚁题解
    8月11日总结
    8月10总结
    PHP 关于获取客户端ip的方法
    PHP内置函数大全
    PHP header函数设置http头
    获取两个日期之间的全部的日期数据(包括两个日期)
    根据周日获取这周的周日到周六的日期(周日为这周的第一天)
  • 原文地址:https://www.cnblogs.com/lovellll/p/10138785.html
Copyright © 2011-2022 走看看