1. 程式人生 > >[Vue CLI 3] vue inspect 的源碼設計實現

[Vue CLI 3] vue inspect 的源碼設計實現

efi == const 實現 cep desc 我們 nds map

首先,請記住:

它在新版本的腳手架項目裏面非常重要

它有什麽用呢?

inspect internal webpack config

能快速地在控制臺看到對應生成的 webpack 配置對象。

首先它是 vue 的一個擴展命令,在文件 @vue/cli/bin/vue.js 中定義了 command

還是依賴了工具包 commander


const program = require(‘commander‘)

代碼配置如下:


program
  .command(‘inspect [paths...]‘)
  .description(‘inspect the webpack config in a project with vue-cli-service‘)
  .option(‘--mode <mode>‘)
  .option(‘--rule <ruleName>‘, ‘inspect a specific module rule‘)
  .option(‘--plugin <pluginName>‘, ‘inspect a specific plugin‘)
  .option(‘--rules‘, ‘list all module rule names‘)
  .option(‘--plugins‘, ‘list all plugin names‘)
  .option(‘-v --verbose‘, ‘Show full function definitions in output‘)
  .action((paths, cmd) => {
    require(‘../lib/inspect‘)(paths, cleanArgs(cmd))
  })

這裏的 option 比較多:

  • mode
  • rule
  • plugin
  • rules
  • plugins
  • verbose

在前面的文章中,我們比較常用的有 rule 相關的

再接著看一下 lib/inspect.js 文件:接受 2 個參數:

  • paths
  • args

module.exports = function inspect (paths, args) {
}

核心還是找到 @vue/cli-service,先獲取當前執行命令的目錄:


const cwd = process.cwd()

let servicePath = resolve.sync(‘@vue/cli-service‘, { basedir: cwd })

最終執行了 node ***/node_modules/@vue/cli-service/bin/vue-cli-service.js inspect 再帶上參數:

調用了工具包 execa


const execa = require(‘execa‘)

execa(‘node‘, [
  binPath,
  ‘inspect‘,
  ...(args.mode ? [‘--mode‘, args.mode] : []),
  ...(args.rule ? [‘--rule‘, args.rule] : []),
  ...(args.plugin ? [‘--plugin‘, args.plugin] : []),
  ...(args.rules ? [‘--rules‘] : []),
  ...(args.plugins ? [‘--plugins‘] : []),
  ...(args.verbose ? [‘--verbose‘] : []),
  ...paths
], { cwd, stdio: ‘inherit‘ })

那我們接著往下看,後面就是去 cli-service 目錄了:@vue/cli-service/lib/commands/inspect.js

通過 api.registerCommand 來註冊一個:


module.exports = (api, options) => {
  api.registerCommand(‘inspect‘, {

  }, args => {

  })
}

在回調函數裏面會處理之前的 option 傳遞的參數:

1、處理 rule


if (args.rule) {
  res = config.module.rules.find(r => r.__ruleNames[0] === args.rule)
}

2、處理 plugin


if (args.plugin) {
  res = config.plugins.find(p => p.__pluginName === args.plugin)
}

3、處理 rules


if (args.rules) {
  res = config.module.rules.map(r => r.__ruleNames[0])
}

4、處理 plugins


if (args.plugins) {
  res = config.plugins.map(p => p.__pluginName || p.constructor.name)
}

其他分支情況比較少用,暫時不做展開。

最後多是通過 webpack-chaintoString 函數來生成,最終在控制臺打印:

You can inspect the generated webpack config using config.toString(). This will generate a stringified version of the config with comment hints for named rules, uses and plugins.

const { toString } = require(‘webpack-chain‘)
const output = toString(res, { verbose })

來源:https://segmentfault.com/a/1190000016260585

[Vue CLI 3] vue inspect 的源碼設計實現