文件门路:VUE 3.0 源码 /script/build.js

整个脚本从入口函数run() 的运行开展,大略经验了如下几个过程:

1、依据是否正式 release 版本,为 true 时须要革除build缓存,防止过期的枚举值;

2、解析命令行参数是否指定了须要编译的模块信息,如果没有将编译所有模块;

3、最终build的过程是执行rollup进行打包

4、另外还有build types过程,将ts源码转成js之后,会生成一堆 *.d.ts,还能够生成 api 报告,生成文档形容模型(xxx.api.json)等

5、正式prd环境还会查看 *.global.prod.js 文件不同压缩形式大小。

具体源码如下:

// nodejs模块:fs-extra 是 fs模块的扩大,提供了更多便当的 API,并继承了fs模块的 APIconst fs = require('fs-extra')const path = require('path') /** nodejs模块:提供文件门路相干api */const chalk = require('chalk') /** nodejs模块:作用是批改控制台中字符串的款式 */const execa = require('execa') /* 具体解释见调用处 */const { gzipSync } = require('zlib') /* nodejs模块: 应用 Gzip 压缩数据块 */const { compress } = require('brotli') /* google 开源的 brotli 压缩算法 */const { targets: allTargets, fuzzyMatchTarget } = require('./utils')/** * minimist 轻量级的命令行参数解析引擎 * process.argv.slice(2) 对应 执行命令参数地位 * (即第3个起始位,对等下例中"-x 3 -y 4 -n 5 -abc --beep=boop foo bar baz"这部分数据) 实例如下: * node example/parse.js -x 3 -y 4 -n 5 -abc --beep=boop foo bar baz * args 后果为:{ *      _: [ 'foo', 'bar', 'baz' ], *      x: 3, *      y: 4, *      n: 5, *      a: true, *      b: true, *      c: true, *      beep: 'boop' *  } */const args = require('minimist')(process.argv.slice(2))// 须要编译的模块数组const targets = args._// console.log('@@@@@@@@@@@@@@@ targets:', targets, args);// 获取 命令行参数中输出的 formats 参数 如 'esm-bundler,cjs' 多个值时两头可用逗号分隔const formats = args.formats || args.fconst devOnly = args.devOnly || args.dconst prodOnly = !devOnly && (args.prodOnly || args.p)const sourceMap = args.sourcemap || args.s// 正式 release 版本,为 true 时须要革除build缓存,防止过期的枚举值const isRelease = args.release// TS API 解析:输入*.d.ts、*.api.md api报告、*.api.json文档形容模型、Markdown文档const buildTypes = args.t || args.types || isRelease// 设置了此参数,将返回targets 中所有匹配胜利的后果;false时只返回第一个匹配胜利的后果const buildAllMatching = args.all || args.a/** * execa * 第1个参数:string类型 相似在cmd中运行脚本的时候敲的命令 * 第2个参数:string[]  跟第1个参数绑定的命令的相干属性信息 * * git rev-parse HEAD --> 获取最新commit id (例如:0996f0ac76188c324831f19089bdd87b9c364cb6) * commit 值为 commit id 前7位 * commit = *.slice(0, 7) = '0996f0a' * */const commit = execa.sync('git', ['rev-parse', 'HEAD']).stdout.slice(0, 7)run()async function run() {  if (isRelease) {    // remove build cache for release builds to avoid outdated enum values    await fs.remove(path.resolve(__dirname, '../node_modules/.rts2_cache'))  }  // 如果命令行中没有指定编译模块时,则编译所有模块  if (!targets.length) {    await buildAll(allTargets)    checkAllSizes(allTargets)  } else {    // 编译 命令行中 指定模块    await buildAll(fuzzyMatchTarget(targets, buildAllMatching))    checkAllSizes(fuzzyMatchTarget(targets, buildAllMatching))  }}async function buildAll(targets) {  for (const target of targets) {    await build(target)  }}async function build(target) {  const pkgDir = path.resolve(`packages/${target}`)  const pkg = require(`${pkgDir}/package.json`)  // only build published packages for release  if (isRelease && pkg.private) {    // 正式公布时,不打包公有模块    return  }  // if building a specific format, do not remove dist.  // 定义了 模块打包类型时,须要革除历史打包数据  if (!formats) {    await fs.remove(`${pkgDir}/dist`)  }  const env =    (pkg.buildOptions && pkg.buildOptions.env) ||    (devOnly ? 'development' : 'production')  /**   * execa   * 第1个参数:string类型 相似在cmd中运行脚本的时候敲的命令   * 第2个参数:string[]  跟第1个参数绑定的命令的相干属性信息   * 第3个参数:execa.Options<string>   * rollup -wc --environment TARGET:[target],FORMATS:umd   *   * -wc: -w 和 -c 组合,-c 应用配置文件 rollup.config.js 打包 js ,-w 观测源文件变动,并主动从新打包   *   * –environment: 设置传递到文件中的环境变量,能够在JS文件中,通过 process.env 读取   * 这里设置了:process.env.COMMIT、process.env.TARGET 等几个变量   *   */  await execa(    'rollup',    [      '-c',      '--environment',      [        `COMMIT:${commit}`,        `NODE_ENV:${env}`,        `TARGET:${target}`,        formats ? `FORMATS:${formats}` : ``,        buildTypes ? `TYPES:true` : ``,        prodOnly ? `PROD_ONLY:true` : ``,        sourceMap ? `SOURCE_MAP:true` : ``      ]        .filter(Boolean)        /**         * filter(Boolean) 移除所有的 ”false“ 类型元素,Boolean 是个函数         * const a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];         * a.filter(Boolean); // [1,2,"b",{},3,5]         */        .join(',')    ],    /**     * stdio选项用于配置在父过程和子过程之间建设的管道     * 默认状况下,子过程的stdin、stdout和stderr被重定向到相应的 subprocess.stdin, subprocess.stdout, subprocess.stderr 所属ChildProcess对象的流。     * 这相当于 options.stdio = ['inherit','inherit','inherit']     */    { stdio: 'inherit' }  )  if (buildTypes && pkg.types) {    console.log()    console.log(      chalk.bold(chalk.yellow(`Rolling up type definitions for ${target}...`))    )    /**     * build types     * @microsoft/api-extractor 的大抵工作流程如下:     * 1、tsc将ts源码转成js之后,会生成一堆 *.d.ts     * 2、API Extractor 通过读取这些 d.ts     *  2.1 能够生成 api 报告     *  2.2 将凌乱的 d.ts 打包并删减     *  2.3 生成文档形容模型(xxx.api.json)能够通过微软提供的 api-documenter 进一步转换成 Markdown文档。     */    const { Extractor, ExtractorConfig } = require('@microsoft/api-extractor')    // 读取extractor配置文件门路(package.json同级目录下的 api-extractor.json)    const extractorConfigPath = path.resolve(pkgDir, `api-extractor.json`)    // 加载api-extractor.json配置文件,并返回一个'ExtractorConfig'对象    const extractorConfig = ExtractorConfig.loadFileAndPrepare(      extractorConfigPath    )    // 应用已筹备好的'ExtractorConfig'对象调用API提取器。    const extractorResult = Extractor.invoke(extractorConfig, {      // 示意API提取器作为本地build的一部分运行,例如在开发人员的计算机上。默认:false      localBuild: true,      // 如果为true,API提取器将输入蕴含{@link ExtractorLogLevel.Verbose}冗余音讯。      showVerboseMessages: true    })    // 提取胜利    if (extractorResult.succeeded) {      // concat additional d.ts to rolled-up dts      const typesDir = path.resolve(pkgDir, 'types')      // 以后编译模块根目录下是否存在 types 目录(eg. packages\vue\types)      if (await fs.exists(typesDir)) {        /**         * pkg.types: package.json中types属性(如:dist/vue.d.ts)         * dtsPath: eg. (\packages\vue\dist\vue.d.ts)         */        const dtsPath = path.resolve(pkgDir, pkg.types)        // 读取 packages/vue/dist/vue.d.ts        const existing = await fs.readFile(dtsPath, 'utf-8')        /**         * 读取typesDir(eg. packages\vue\types) 目录下文件         * 返回:typeFiles = [ 'vue.d.ts' ]         */        const typeFiles = await fs.readdir(typesDir)        // 遍历读取 typeFiles = [ 'vue.d.ts' ] 文件信息,返回到 toAdd 列表中        const toAdd = await Promise.all(          typeFiles.map(file => {            return fs.readFile(path.resolve(typesDir, file), 'utf-8')          })        )        // 将 typesDir(eg. packages\vue\types) 目录下所有*.d.ts 文件信息汇总到一个文件中        // dtsPath: eg. (\packages\vue\dist\vue.d.ts)        await fs.writeFile(dtsPath, existing + '\n' + toAdd.join('\n'))      }      console.log(        chalk.bold(chalk.green(`API Extractor completed successfully.`))      )    } else {      console.error(        `API Extractor completed with ${extractorResult.errorCount} errors` +          ` and ${extractorResult.warningCount} warnings`      )      process.exitCode = 1    }    await fs.remove(`${pkgDir}/dist/packages`)  }}function checkAllSizes(targets) {  if (devOnly) {    return  }  console.log()  for (const target of targets) {    checkSize(target)  }  console.log()}function checkSize(target) {  const pkgDir = path.resolve(`packages/${target}`)  checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)}/** * 查看 *.global.prod.js 文件不同压缩形式大小 * vue.global.prod.js min:100.07kb / gzip:38.20kb / brotli:34.33kb * min: 元素大小 * gzip:应用 nodejs 模块 - Gzip 压缩数据块 * brotli: google 开源的 brotli 压缩算法 */function checkFileSize(filePath) {  if (!fs.existsSync(filePath)) {    return  }  const file = fs.readFileSync(filePath)  const minSize = (file.length / 1024).toFixed(2) + 'kb'  const gzipped = gzipSync(file)  const gzippedSize = (gzipped.length / 1024).toFixed(2) + 'kb'  const compressed = compress(file)  const compressedSize = (compressed.length / 1024).toFixed(2) + 'kb'  console.log(    `${chalk.gray(      chalk.bold(path.basename(filePath))    )} min:${minSize} / gzip:${gzippedSize} / brotli:${compressedSize}`  )}

如果您对 “前端源码” 情有独钟,可微信关注前端源码解析公众号,内容继续更新中!

以后 VUE3.0 源码正在解析中,欢送捧场!


~