Home > Web Front-end > Vue.js > Vite Learning's Deep Analysis 'Dependency Scanning'

Vite Learning's Deep Analysis 'Dependency Scanning'

青灯夜游
Release: 2022-09-05 18:13:55
forward
1691 people have browsed it

This article will give you an in-depth explanation of the implementation details of dependency scanning in Vite. The final scanning result is an object containing the names of multiple modules. It does not involve the pre-building process or how the pre-built products are used.

Vite Learning's Deep Analysis 'Dependency Scanning'

When we run Vite for the first time, Vite will perform dependency pre-building in order to be compatible with CommonJS and UMD. And Improve performance. [Related recommendations: vuejs video tutorial]

To pre-build dependencies, you must first understand these two issues:

  • Pre-build What is the content of ? / Which modules need to be pre-built?

  • How to find the modules that need to be pre-built?

These two problems are actually dependence on the content of scanning and the implementation method.

This article will explain the implementation details of dependency scanning in depth. The final scanning result is an object containing the names of multiple modules. It does not involve the pre-building process or how the pre-built product is. in use. If you are interested in this part of the content, you can follow me and wait for subsequent articles.

Depend on pre-built content

There are many modules in a project, and not all modules will be pre-built.

Only bare import (bare dependency) will perform dependency pre-building

What is bare import?

Look directly at the example below

// vue 是 bare import
import xxx from "vue"
import xxx from "vue/xxx"

// 以下不是裸依赖
import xxx from "./foo.ts" 
import xxx from "/foo.ts"
Copy after login
You can divide it simply:

    The module accessed by name is a bare module
  • Modules accessed using paths are not bare import
In fact, Vite also judges this.

The following is the module dependency tree of a common

Vue project

Vite Learnings Deep Analysis Dependency Scanning

The results of the dependency scan are as follows:

[ "vue", "axios" ]
Copy after login
Why only bare import is pre-built?

Node.js defines the addressing mechanism of bare import - Search under node_modules in the current directory. If not found, go to node_modules in the upper directory until The directory is the root path and cannot go higher.

bare import is usually a module installed by npm. It is a third-party module, not the code we wrote ourselves. Generally, will not be modified. Therefore, executing the construction of these modules in advance will help improve performance.

On the contrary, if the code written by the developer is pre-built, the project is packaged into a chunk file.

When the developer modifies the code, he needs to re-perform the build and then package it into a chunk file. , this process will actually affect performance.

Will modules under monorepo also be pre-built?

Won't. Because in the case of monorepo, although some modules are bare import, these modules are also written by the developers themselves and are not third-party modules, so Vite does not pre-build these modules.

Actually, Vite will

determine whether the actual path of the module is in node_modules :

    The module with the actual path in node_modules will be pre-built, this is Third-party modules
  • If the actual path is not in node_modules, it proves that the module is linked to node_modules through a file link (the implementation of monorepo). It is the code written by the developer himself and does not perform pre-building

Dependency scanning

Implementation ideas

Let’s take a look at this module dependency tree again :

Vite Learnings Deep Analysis Dependency Scanning

To scan out all bare imports, you need to traverse the entire dependency tree, which involves a deep traversal of the

tree

When we discuss tree traversal, we generally focus on these two points:

    When to stop going deep?
  • How to deal with leaf nodes?

Vite Learnings Deep Analysis Dependency Scanning

The current leaf node does not need to be traversed in depth:

    When encountering a bare import node, record the dependency , there is no need to continue to traverse in depth
  • When you encounter other modules that have nothing to do with JS, such as CSS, SVG, etc., because they are not JS codes, there is no need to continue to traverse in depth

When all leaf nodes are traversed, the recorded bare import object is the result of the dependency scan.

The implementation idea of ​​relying on scanning is actually very easy to understand, but the actual processing is not simple.

Let’s take a look at the processing of leaf nodes:

  • bare import

It can be judged by the module id. The module whose module id is not a path is bare import. When encountering these modules, record the dependencies and no longer traverse in depth.

  • Other JS-independent modules

You can judge by the suffix name of the module, for example, if you encounter *.css Module, does not require any processing, and no further traversal is required.

  • JS module

To obtain the dependent submodules in the JS code, you need to convert the code into AST and obtain the module introduced by the import statement, or Regularly match all imported modules , and then continue to traverse these modules in depth

  • HTML type module

This type of module is more complicated. For example, HTML or Vue contains part of JS. You need toextract this part of the JS code, and then analyze and process it according to the JS module. Continue to traverse these modules in depth. We only need to care about the JS part here, and modules will not be introduced in other parts.

Vite Learnings Deep Analysis Dependency Scanning

Specific implementation

We already know the implementation idea of ​​dependency scanning,The idea is actually It's not complicated. What's complicated is the processing , especially the processing of HTML, Vue and other modules.

Vite uses a more clever method here - Packaging with the esbuild tool

Why can esbuild packaging be used to replace the deep traversal process?

EssentiallyThe packaging process is also a process of deep traversal of modules. The alternative method is as follows:

Depth traversal esbuild packaging
Processing of leaf nodes esbuild can perform each module (leaf node) Parsing and loading
These two processes can be extended through plug-ins and add some special logic
For example, convert html to js during the loading process
Do not process the module in depth esbuild can specify the currently parsed module as external
during the parsing process, then esbuild will no longer parse and load the module in depth Module .
Traverse the module in depth Parse the module normally (do nothing, esbuild default behavior), return the real path of the module’s file

It doesn’t matter if you don’t understand this part for now, there will be examples later

Vite Learnings Deep Analysis Dependency Scanning

Processing of various modules

##bare importDuring the parsing process, Other JS-independent modules During the parsing process, JS moduleJust parse and load normally, esbuild itself can handle JShtml type module During the loading process, these modules

最后 dep 对象中收集到的依赖就是依赖扫描的结果,而这次 esbuild 的打包产物,其实是没有任何作用的,在依赖扫描过程中,我们只关心每个模块的处理过程,不关心构建产物

用 Rollup 处理可以吗?

其实也可以,打包工具基本上都会有解析和加载的流程,也能对模块进行 external

但是 esbuild 性能更好

html 类型的模块处理

这类文件有 htmlvue 等。之前我们提到了要将它们转换成 JS,那么到底要如何转换呢?

Vite Learnings Deep Analysis Dependency Scanning

由于依赖扫描过程,只关注引入的 JS 模块,因此可以直接丢弃掉其他不需要的内容,直接取其中 JS

html 类型文件(包括 vue)的转换,有两种情况:

  • 每个外部 script,会直接转换为 import 语句,引入外部 script
  • 每个内联 script,其内容将会作为虚拟模块被引入。

什么是虚拟模块?

是模块的内容并非直接从磁盘中读取,而是编译时生成

举个例子,src/main.ts 是磁盘中实际存在的文件,而 virtual-module:D:/project/index.html?id=0 在磁盘中是不存在的,需要借助打包工具(如 esbuild),在编译过程生成。

为什么需要虚拟模块?

因为一个 html 类型文件中,允许有多个 script 标签,多个内联的 script 标签,其内容无法处理成一个 JS 文件 (因为可能会有命名冲突等原因)

既然无法将多个内联 script,就只能将它们分散成多个虚拟模块,然后分别引入了。

源码解析

依赖扫描的入口

下面是扫描依赖的入口函数(为了便于理解,有删减和修改):

import { build } from 'esbuild'
export async function scanImports(config: ResolvedConfig): Promise
  missing: Record<string>
}> {
    
  // 将项目中所有的 html 文件作为入口,会排除 node_modules
  let entries: string[] = await globEntries('**/*.html', config)

  // 扫描到的依赖,会放到该对象
  const deps: Record<string> = {}
  // 缺少的依赖,用于错误提示
  const missing: Record<string> = {}
  
  // esbuild 扫描插件,这个是重点!!!
  const plugin = esbuildScanPlugin(config, container, deps, missing, entries)

  // 获取用户配置的 esbuild 自定义配置,没有配置就是空的
  const { plugins = [], ...esbuildOptions } =
    config.optimizeDeps?.esbuildOptions ?? {}

  await Promise.all(
    // 入口可能不止一个,分别用 esbuid 打包
    entries.map((entry) =>
      // esbuild 打包
      build({
        absWorkingDir: process.cwd(),
        write: false,
        entryPoints: [entry],
        bundle: true,
        format: 'esm',
        // 使用插件
        plugins: [...plugins, plugin],
        ...esbuildOptions
      })
    )
  )

  return {
    deps,
    missing
  }
}</string></string></string>
Copy after login

主要流程如下:

  • 将项目内所有的 html 作为入口文件(排除 node_modules)。

  • 将每个入口文件,用 esbuild 进行打包

这里的核心其实是 esbuildScanPlugin 插件的实现,它定义了各类模块(叶子节点)的处理方式。

function esbuildScanPlugin(config, container, deps, missing, entries){}
Copy after login
  • depmissing对象被当做入参传入,在函数中,这两个对象的内容会在打包(插件运行)过程中被修改

esbuild 插件

很多同学可能不知道 esbuild 插件是如何编写的,这里简单介绍一下:

每个模块都会经过解析(resolve)和加载(load)的过程:

  • 解析:将模块路径,解析成文件真实的路径。例如 vue,会解析到实际 node_modules 中的 vue 的入口 js 文件
  • 加载:根据解析的路径,读取文件的内容

Vite Learnings Deep Analysis Dependency Scanning

插件可以定制化解析和加载的过程,下面是一些插件示例代码:

const plugin = {
    name: 'xxx',
    setup(build) {
        
        // 定制解析过程,所有的 http/https 的模块,都会被 external
        build.onResolve({ filter: /^(https?:)?\/\// }, ({ path }) => ({
            path,
            external: true
        }))
        
        // 定制解析过程,给所有 less 文件 namespace: less 标记
        build.onResolve({ filter: /.*\.less/ }, args => ({
            path: args.path,
            namespace: 'less',
        }))

        // 定义加载过程:只处理 namespace 为 less 的模块
        build.onLoad({ filter: /.*/, namespace: 'less' }, () => {
            const raw = fs.readFileSync(path, 'utf-8')
            const content = // 省略 less 处理,将 less 处理成 css
            return {
                contents,
                loader: 'css'
        	}
        })
    }
}
Copy after login
  • 通过 onResolveonLoad 定义解析和加载过程
  • onResolve 的第一个参数为过滤条件,第二个参数为回调函数,解析时调用,返回值可以给模块做标记,如 externalnamespace(用于过滤),还需要返回模块的路径
  • 每个模块, onResolve 会被依次调用,直到回调函数返回有效的值,后面的不再调用。如果都没有有效返回,则使用默认的解析方式
  • onLoad  的第一个参数为过滤条件,第二个参数为回调函数,加载时调用,可以读取文件的内容,然后进行处理,最后返回加载的内容
  • 每个模块,onLoad 会被依次调用,直到回调函数返回有效的值,后面的不再调用。如果都没有有效返回,则使用默认的加载方式。

扫描插件的实现

function esbuildScanPlugin(
  config: ResolvedConfig,
  container: PluginContainer,
  depImports: Record<string>,
  missing: Record<string>,
  entries: string[]
): Plugin</string></string>
Copy after login

部分参数解析:

  • config:Vite 的解析好的用户配置

  • container:这里只会用到 container.resolveId 的方法,这个方法能将模块路径转成真实路径

    例如 vue 转成 xxx/node_modules/dist/vue.esm-bundler.js

  • depImports:用于存储扫描到的依赖对象,插件执行过程中会被修改

  • missing:用于存储缺少的依赖的对象,插件执行过程中会被修改

  • entries:存储所有入口文件的数组

esbuild 默认能将模块路径转成真实路径,为什么还要用 container.resolveId

因为 Vite/Rollup 的插件,也能扩展解析的流程,例如 alias 的能力,我们常常会在项目中用 @ 的别名代表项目的 src 路径。

因此不能用 esbuild 原生的解析流程进行解析。

container(插件容器)用于兼容 Rollup 插件生态,用于保证 dev 和 production 模式下,Vite 能有一致的表现。感兴趣的可查看《Vite 是如何兼容 Rollup 插件生态的》

这里  container.resolveId  会被再次包装一成 resolve 函数(多了缓存能力)

const seen = new Map<string>()
const resolve = async (
    id: string,
    importer?: string,
    options?: ResolveIdOptions
) => {
    const key = id + (importer && path.dirname(importer))
    
    // 如果有缓存,就直接使用缓存
    if (seen.has(key)) {
        return seen.get(key)
    }
    // 将模块路径转成真实路径
    const resolved = await container.resolveId(
        id,
        importer && normalizePath(importer),
        {
            ...options,
            scan: true
        }
    )
    // 缓存解析过的路径,之后可以直接获取
    const res = resolved?.id
    seen.set(key, res)
    return res
  }</string>
Copy after login

那么接下来就是插件的实现了,先回顾一下之前写的各类模块的处理:


Example Processing
vue save the naked dependency to the deps object and set it to external
less file is set to external
./mian.ts
index.html, app.vue are loaded into JS

例子 处理
bare import vue 在解析过程中,将裸依赖保存到 deps 对象中,设置为 external
其他 JS 无关的模块 less文件 在解析过程中,设置为 external
JS 模块 ./mian.ts 正常解析和加载即可,esbuild 本身能处理 JS
html 类型模块 index.htmlapp.vue 在加载过程中,将这些模块加载成 JS

JS 模块

esbuild 本身就能处理 JS 语法,因此 JS 是不需要任何处理的,esbuild 能够分析出 JS 文件中的依赖,并进一步深入处理这些依赖。

其他 JS 无关的模块

// external urls
build.onResolve({ filter: /^(https?:)?\/\// }, ({ path }) => ({
    path,
    external: true
}))

// external css 等文件
build.onResolve(
    {
        filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json|wasm)$/
    },
    ({ path }) => ({
        path,
        external: true
    }
)
    
// 省略其他 JS 无关的模块
Copy after login

这部分处理非常简单,直接匹配,然后 external 就行了

bare import

build.onResolve(
  {
    // 第一个字符串为字母或 @,且第二个字符串不是 : 冒号。如 vite、@vite/plugin-vue
    // 目的是:避免匹配 window 路径,如 D:/xxx 
    filter: /^[\w@][^:]/
  },
  async ({ path: id, importer, pluginData }) => {
    // depImports 为
    if (depImports[id]) {
      return externalUnlessEntry({ path: id })
    }
    // 将模块路径转换成真实路径,实际上调用 container.resolveId
    const resolved = await resolve(id, importer, {
      custom: {
        depScan: { loader: pluginData?.htmlType?.loader }
      }
    })
    
    // 如果解析到路径,证明找得到依赖
    // 如果解析不到路径,则证明找不到依赖,要记录下来后面报错
    if (resolved) {
      if (shouldExternalizeDep(resolved, id)) {
        return externalUnlessEntry({ path: id })
      }
      // 如果模块在 node_modules 中,则记录 bare import
      if (resolved.includes('node_modules')) {
        // 记录 bare import
        depImports[id] = resolved

        return {
        	path,
        	external: true
   		}
      } 
      // isScannable 判断该文件是否可以扫描,可扫描的文件有 JS、html、vue 等
      // 因为有可能裸依赖的入口是 css 等非 JS 模块的文件
      else if (isScannable(resolved)) {
        // 真实路径不在 node_modules 中,则证明是 monorepo,实际上代码还是在用户的目录中
        // 是用户自己写的代码,不应该 external
        return {
          path: path.resolve(resolved)
        }
      } else {
        // 其他模块不可扫描,直接忽略,external
        return {
            path,
            external: true
        }
      }
    } else {
      // 解析不到依赖,则记录缺少的依赖
      missing[id] = normalizePath(importer)
    }
  }
)
Copy after login
  • 如果文件在 node_modules 中,才认为是 bare import,记录当前模块
  • 文件不在 node_modules 中,则是 monorepo,是用户自己写的代码
    • 如果这些代码 isScanable 可扫描(即含有 JS 代码),则继续深入处理
    • 其他非 JS 模块,external

html 类型模块

如: index.htmlapp.vue

const htmlTypesRE = /\.(html|vue|svelte|astro)$/

// html types: 提取 script 标签
build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => {
    // 将模块路径,转成文件的真实路径
    const resolved = await resolve(path, importer)
    if (!resolved) return
    
    // 不处理 node_modules 内的
    if (resolved.includes('node_modules'){
        return
   }

    return {
        path: resolved,
        // 标记 namespace 为 html 
        namespace: 'html'
    }
})
Copy after login

解析过程很简单,只是用于过滤掉一些不需要的模块,并且标记 namespace 为 html

真正的处理在加载阶段:

Vite Learnings Deep Analysis Dependency Scanning

// 正则,匹配例子: <script></script>
const scriptModuleRE = /(<script>]*type\s*=\s*(?:"module"|&#39;module&#39;)[^>]*>)(.*?)<\/script>/gims
// 正则,匹配例子: <script></script>
export const scriptRE = /(<script>]*>|>))(.*?)<\/script>/gims

build.onLoad(
    { filter: htmlTypesRE, namespace: &#39;html&#39; },
    async ({ path }) => {
        // 读取源码
        let raw = fs.readFileSync(path, &#39;utf-8&#39;)
        // 去掉注释,避免后面匹配到注释
        raw = raw.replace(commentRE, &#39;<!---->&#39;)

        const isHtml = path.endsWith(&#39;.html&#39;)
        // scriptModuleRE: <script type=module></script>
        // scriptRE: <script></script>
        // html 模块,需要匹配 module 类型的 script,因为只有 module 类型的 script 才能使用 import
        const regex = isHtml ? scriptModuleRE : scriptRE

        // 重置正则表达式的索引位置,因为同一个正则表达式对象,每次匹配后,lastIndex 都会改变
        // regex 会被重复使用,每次都需要重置为 0,代表从第 0 个字符开始正则匹配
        regex.lastIndex = 0
        // load 钩子返回值,表示加载后的 js 代码
        let js = ''
        let scriptId = 0
        let match: RegExpExecArray | null

        // 匹配源码的 script 标签,用 while 循环,因为 html 可能有多个 script 标签
        while ((match = regex.exec(raw))) {
            // openTag: 它的值的例子: <script>
            // content: script 标签的内容
            const [, openTag, content] = match
            
            // 正则匹配出 openTag 中的 type 和 lang 属性
            const typeMatch = openTag.match(typeRE)
            const type =
                  typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3])
            const langMatch = openTag.match(langRE)
            const lang =
                  langMatch && (langMatch[1] || langMatch[2] || langMatch[3])
            
            // 跳过 type="application/ld+json" 和其他非 non-JS 类型
            if (
                type &&
                !(
                    type.includes(&#39;javascript&#39;) ||
                    type.includes(&#39;ecmascript&#39;) ||
                    type === &#39;module&#39;
                )
            ) {
                continue
            }
            
            // esbuild load 钩子可以设置 应的 loader
            let loader: Loader = &#39;js&#39;
            if (lang === &#39;ts&#39; || lang === &#39;tsx&#39; || lang === &#39;jsx&#39;) {
                loader = lang
            } else if (path.endsWith(&#39;.astro&#39;)) {
                loader = &#39;ts&#39;
            }
            
            // 正则匹配出 script src 属性
            const srcMatch = openTag.match(srcRE)
            // 有 src 属性,证明是外部 script
            if (srcMatch) {
                
                const src = srcMatch[1] || srcMatch[2] || srcMatch[3]
                // 外部 script,改为用 import 用引入外部 script
                js += `import ${JSON.stringify(src)}\n`
            } else if (content.trim()) {
                // 内联的 script,它的内容要做成虚拟模块

                // 缓存虚拟模块的内容
                // 一个 html 可能有多个 script,用 scriptId 区分
                const key = `${path}?id=${scriptId++}`
                scripts[key] = {
                    loader,
                    content,
                    pluginData: {
                        htmlType: { loader }
                    }
                }

                // 虚拟模块的路径,如 virtual-module:D:/project/index.html?id=0
                const virtualModulePath = virtualModulePrefix + key
                js += `export * from ${virtualModulePath}\n`
            }
        }

        return {
            loader: &#39;js&#39;,
            contents: js
        }
    }
)</script>
Copy after login

加载阶段的主要做有以下流程:

  • 读取文件源码
  • 正则匹配出所有的 script 标签,并对每个 script 标签的内容进行处理
    • 外部 script,改为用 import 引入
    • 内联 script,改为引入虚拟模块,并将对应的虚拟模块的内容缓存到 script 对象。
  • 最后返回转换后的 js

srcMatch[1] || srcMatch[2] || srcMatch[3] 是干嘛?

我们来看看匹配的表达式:

const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im
Copy after login

因为 src 可以有以下三种写法:

  • src="xxx"
  • src='xxx'
  • src=xxx

三种情况会出现其中一种,因此是三个捕获组

虚拟模块是如何加载成对应的 script 代码的?

export const virtualModuleRE = /^virtual-module:.*/

// 匹配所有的虚拟模块,namespace 标记为 script
build.onResolve({ filter: virtualModuleRE }, ({ path }) => {
  return {
    // 去掉 prefix
    // virtual-module:D:/project/index.html?id=0 => D:/project/index.html?id=0
    path: path.replace(virtualModulePrefix, ''),
    namespace: 'script'
  }
})

// 之前的内联 script 内容,保存到 script 对象,加载虚拟模块的时候取出来
build.onLoad({ filter: /.*/, namespace: 'script' }, ({ path }) => {
  return scripts[path]
})
Copy after login

虚拟模块的加载很简单,直接从 script 对象中,读取之前缓存起来的内容即可。

这样之后,我们就可以把 html 类型的模块,转换成 JS 了

扫描结果

下面是一个  depImport 对象的例子:

{
  "vue": "D:/app/vite/node_modules/.pnpm/vue@3.2.37/node_modules/vue/dist/vue.runtime.esm-bundler.js",
  "vue/dist/vue.d.ts": "D:/app/vite/node_modules/.pnpm/vue@3.2.37/node_modules/vue/dist/vue.d.ts",
  "lodash-es": "D:/app/vite/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/lodash.js"
}
Copy after login
  • key:模块名称
  • value:模块的真实路径

总结

依赖扫描是预构建前的一个非常重要的步骤,这决定了 Vite 需要对哪些依赖进行预构建。

本文介绍了 Vite 会对哪些内容进行依赖预构建,然后分析了实现依赖扫描的基本思路 —— 深度遍历依赖树,并对各种类型的模块进行处理。然后介绍了 Vite 如何巧妙的使用 esbuild 实现这一过程。最后对这部分的源码进行了解析:

  • 最复杂的就是 html 类型模块的处理,需要使用虚拟模块
  • 当遇到 bare import 时,需要判断是否在 node_modules 中,在的才记录依赖,然后  external。
  • 其他 JS 无关的模块就直接 external
  • JS 模块由于 esbuild 本身能处理,不需要做任何的特殊操作

最后获取到的 depImport 是一个记录依赖以及其真实路径的对象

(学习视频分享:web前端开发编程基础视频

The above is the detailed content of Vite Learning's Deep Analysis 'Dependency Scanning'. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template