vite源码阅读1:index.cjs

/* eslint-disable no-restricted-globals */
// 禁用 ESLint 的 no-restricted-globals 规则,不进行全局变量的限制检查

// type utils
module.exports.defineConfig = (config) => config

// proxy cjs utils (sync functions)
// 通过 Object.assign 将 ./dist/node-cjs/publicUtils.cjs 模块中的函数挂载到模块的导出上
Object.assign(module.exports, require('./dist/node-cjs/publicUtils.cjs'))

// async functions, can be redirect from ESM build
// 异步函数,可以从ESM构建中重定向
// 这样做的目的是将这些异步函数调用时动态地从 ./dist/node/index.js 模块中导入,实现了按需加载的效果
const asyncFunctions = [
  'build',
  'createServer',
  'preview',
  'transformWithEsbuild',
  'resolveConfig',
  'optimizeDeps',
  'formatPostcssSourceMap',
  'loadConfigFromFile',
  'preprocessCSS',
]
asyncFunctions.forEach((name) => {
    
    
  module.exports[name] = (...args) =>
    import('./dist/node/index.js').then((i) => i[name](...args))
})

// some sync functions are marked not supported due to their complexity and uncommon usage
// 一些同步函数由于其复杂性和不常见的使用方式而被标记为不支持
// 简单来说,就是这两个函数不支持commonjs,当在commonjs中使用时需要报错提示,提示使用ESM或者动态导入
const unsupportedCJS = ['resolvePackageEntry', 'resolvePackageData']
unsupportedCJS.forEach((name) => {
    
    
  module.exports[name] = () => {
    
    
    // ESM是JavaScript的官方模块系统,使用import和export关键字来导入和导出模块。
    // 动态导入(dynamic imports)是一种在运行时根据条件或需要来动态加载模块的方式。它使用import()函数来实现,函数返回一个Promise,在Promise解析后可以访问导入的模块。
    // 两种方式的区别在于使用时机和语法形式。ESM适用于在模块的顶层直接导入使用,而动态导入适用于在运行时根据需要动态加载模块。
    throw new Error(
      `"${
      
      name}" is not supported in CJS build of Vite 4.\nPlease use ESM or dynamic imports \`const { ${
      
      name} } = await import('vite')\`.`,
    )
  }
})

猜你喜欢

转载自blog.csdn.net/qq_42611074/article/details/131071431