组件渲染

前面的章节我们说到了本地文件在发送给浏览器之前是会根据文件类型做不同的 transfrom 代码转换的。 组件渲染 - 图1 观察一下我们实际在浏览器中加载的文件内容。可以看到表面我们加载的是一个 .vue 组件。但是文件的实际内容还是传统的 .js 文件,并且 Content-Type 也是 application/javascript; charset=utf-8 所以浏览器才能够直接运行该文件。并且我们可以发现不同的文件类型后面跟的 query type 参数也不一样。有 ?type=template ?type=import。下面让我们来具体分析一下一个 Vue 组件是如何在浏览器中被渲染的吧

处理 css 文件

浏览器是不支持直接 import 导入 .css 文件的。如果你配置过 webpack 来处理 css 文件,那么你应该清楚这类问题的解决方式要么是将 css 编译成 js 文件,要么是把组件中的 css 单独提取为 css文件通过 link 标签来进行加载。Vite 在本地开发时采用的是第一种方式,在生产环境构建时仍然是编译成独立的 css 文件进行加载。

挂载样式

Vite 使用 serverPluginCss 插件来处理形如 http://localhost:3000/src/index.css?import 这样的以.css为后缀结尾且 query 包含 import 的请求。

  1. // src/node/server/serverPluginCss.ts
  2. const id = JSON.stringify(hash_sum(ctx.path))
  3. if (isImportRequest(ctx)) {
  4. const { css, modules } = await processCss(root, ctx) // 这里主要对css文件做一些预处理之类的操作如 less->css, postcss之类的处理不在此处详细展开
  5. console.log(modules)
  6. ctx.type = 'js'
  7. ctx.body = codegenCss(id, css, modules)
  8. }
  9. export function codegenCss(
  10. id: string,
  11. css: string,
  12. modules?: Record<string, string>
  13. ): string {
  14. let code =
  15. `import { updateStyle } from "${clientPublicPath}"\n` +
  16. `const css = ${JSON.stringify(css)}\n` +
  17. `updateStyle(${JSON.stringify(id)}, css)\n`
  18. if (modules) {
  19. code += `export default ${JSON.stringify(modules)}`
  20. } else {
  21. code += `export default css`
  22. }
  23. return code
  24. }

在上面的代码中,我们劫持了 css 文件的请求以及重写了请求的响应。将 css 文件改写为 esmodule 格式的js文件。如果启用了 css-modules 则我们导出一个具体对象。因为组件需要使用 :id=styles.xxx 的形式来引用。对于普通的 css 文件则无需导出具体有意义的对象。这里的核心方法是 updateStyle,让我们来看看这个方法到底干了什么。

updateStyle

http://localhost:3000/src/index.css?import 请求的详细响应信息可以看出。实质是 Vite 是通过 updateStyle 这个方法来将 css 字符串挂载到具体的 dom 元素上 组件渲染 - 图2

  1. export function updateStyle(id: string, content: string) {
  2. let style = sheetsMap.get(id)
  3. if (supportsConstructedSheet && !content.includes('@import')) {
  4. if (style && !(style instanceof CSSStyleSheet)) {
  5. removeStyle(id)
  6. style = undefined
  7. }
  8. if (!style) {
  9. style = new CSSStyleSheet()
  10. style.replaceSync(content)
  11. // @ts-ignore
  12. document.adoptedStyleSheets = [...document.adoptedStyleSheets, style]
  13. } else {
  14. style.replaceSync(content)
  15. }
  16. } else {
  17. if (style && !(style instanceof HTMLStyleElement)) {
  18. removeStyle(id)
  19. style = undefined
  20. }
  21. if (!style) {
  22. style = document.createElement('style')
  23. style.setAttribute('type', 'text/css')
  24. style.innerHTML = content
  25. document.head.appendChild(style)
  26. } else {
  27. style.innerHTML = content
  28. }
  29. }
  30. sheetsMap.set(id, style)
  31. }

updateStyle 中用到的核心 API 是 CSSStyleSheet 首先我们在 supportsConstructedSheet 中判断了当前浏览器是否支持 CSSStyleSheet, 如果不支持则采用 style 标签插入的形式挂载样式。 如果支持则创建 CSSStyleSheet 实例。接着将编译后的 css 字符串传入 CSSStyleSheet 实例对象。再将该对象添加进 document.adoptedStyleSheet 就可以让我们的样式生效啦

解析 Vue 文件

Vite 在解析 .vue 文件主要做的还是 code transform 将 vue 组件解析成调用 compile 以及 render 方法的 js 文件。具体的 compile 以及 render 的核心逻辑还是在 vue3 的 api 中完成。

  1. // src/node/server/serverPluginVue.ts
  2. const descriptor = await parseSFC(root, filePath, ctx.body)

首先用官方提供的库来将单文件组件编译成 descriptor。以 App.vue 为例这里我们摘出比较重要的信息省略 sourcemap信息。

  1. // src/App.vue
  2. {
  3. filename: '/Users/yuuang/Desktop/github/vite_test/src/App.vue',
  4. source: '<template>\n' +
  5. ' <img alt="Vue logo" src="./assets/logo.png" :class="style.big"/>\n' +
  6. ' <div class="small">\n' +
  7. ' small1\n' +
  8. ' </div>\n' +
  9. ' <HelloWorld msg="Hello Vue 3.0 + Vite" />\n' +
  10. '</template>\n' +
  11. '\n' +
  12. '<script>\n' +
  13. "import HelloWorld from './components/HelloWorld.vue'\n" +
  14. "import style from './index.module.css'\n" +
  15. '\n' +
  16. 'export default {\n' +
  17. " name: 'App',\n" +
  18. ' components: {\n' +
  19. ' HelloWorld\n' +
  20. ' },\n' +
  21. ' data() {\n' +
  22. ' return {\n' +
  23. ' style: style\n' +
  24. ' }\n' +
  25. ' },\n' +
  26. ' mounted () {\n' +
  27. " console.log('mounted')\n" +
  28. ' }\n' +
  29. '}\n' +
  30. '</script>\n' +
  31. '\n' +
  32. '<style>\n' +
  33. '.small {\n' +
  34. ' width:21px\n' +
  35. '}\n' +
  36. '</style>\n' +
  37. '\n',
  38. template: {
  39. type: 'template',
  40. content: '\n' +
  41. ' <img alt="Vue logo" src="./assets/logo.png" :class="style.big"/>\n' +
  42. ' <div class="small">\n' +
  43. ' small1\n' +
  44. ' </div>\n' +
  45. ' <HelloWorld msg="Hello Vue 3.0 + Vite" />\n',
  46. loc: {
  47. source: '\n' +
  48. ' <img alt="Vue logo" src="./assets/logo.png" :class="style.big"/>\n' +
  49. ' <div class="small">\n' +
  50. ' small1\n' +
  51. ' </div>\n' +
  52. ' <HelloWorld msg="Hello Vue 3.0 + Vite" />\n',
  53. start: [Object],
  54. end: [Object]
  55. },
  56. attrs: {},
  57. map: xxx
  58. },
  59. script: {
  60. type: 'script',
  61. content: '\n' +
  62. "import HelloWorld from './components/HelloWorld.vue'\n" +
  63. "import style from './index.module.css'\n" +
  64. '\n' +
  65. 'export default {\n' +
  66. " name: 'App',\n" +
  67. ' components: {\n' +
  68. ' HelloWorld\n' +
  69. ' },\n' +
  70. ' data() {\n' +
  71. ' return {\n' +
  72. ' style: style\n' +
  73. ' }\n' +
  74. ' },\n'
  75. '}\n',
  76. loc: {
  77. source: '\n' +
  78. "import HelloWorld from './components/HelloWorld.vue'\n" +
  79. "import style from './index.module.css'\n" +
  80. '\n' +
  81. 'export default {\n' +
  82. " name: 'App',\n" +
  83. ' components: {\n' +
  84. ' HelloWorld\n' +
  85. ' },\n' +
  86. ' data() {\n' +
  87. ' return {\n' +
  88. ' style: style\n' +
  89. ' }\n' +
  90. ' },\n'
  91. '}\n',
  92. start: [Object],
  93. end: [Object]
  94. },
  95. attrs: {},
  96. map: xxx
  97. },
  98. scriptSetup: null,
  99. styles: [
  100. {
  101. type: 'style',
  102. content: '\n.small {\n width:21px\n}\n',
  103. loc: [Object],
  104. attrs: {},
  105. map: [Object]
  106. }
  107. ],
  108. customBlocks: []
  109. }

通过上述代码我们可以解析出一个组件的 descriptor。拿到解析结果后继续往下判断

  1. if (!query.type) {
  2. // watch potentially out of root vue file since we do a custom read here
  3. watchFileIfOutOfRoot(watcher, root, filePath)
  4. if (descriptor.script && descriptor.script.src) {
  5. filePath = await resolveSrcImport(
  6. root,
  7. descriptor.script,
  8. ctx,
  9. resolver
  10. )
  11. }
  12. ctx.type = 'js'
  13. const { code, map } = await compileSFCMain(
  14. descriptor,
  15. filePath,
  16. publicPath,
  17. root
  18. )
  19. ctx.body = code
  20. ctx.map = map
  21. return etagCacheCheck(ctx)
  22. }

首先是针对没有特定 query type 的请求。我们首先判断 script 标签有没有 src 属性。例如 <script src="./app.js"></script> 将逻辑单独拆出一个文件进行维护。这种写法在 Vue 中比较少见也不推荐。Vue 推崇单文件组件的写法。接下来就是比较核心的 compileSFCMain 方法了

  1. if (script) {
  2. content = script.content
  3. map = script.map
  4. if (script.lang === 'ts') {
  5. const res = await transform(content, publicPath, {
  6. loader: 'ts'
  7. })
  8. content = res.code
  9. map = mergeSourceMap(map, JSON.parse(res.map!))
  10. }
  11. }
  12. /**
  13. * Utility for rewriting `export default` in a script block into a varaible
  14. * declaration so that we can inject things into it
  15. */
  16. code += rewriteDefault(content, '__script')

首先判断如果是 ts 文件则先调用 esbuild 来将 ts 转换为 js。接着使用 rewriteDefault 来重写 export default 的内容到一个变量中。在这里是 __script。做完之后 code 的内容为

  1. import HelloWorld from './components/HelloWorld.vue'
  2. import style from './index.module.css'
  3. const __script = {
  4. name: 'App',
  5. components: {
  6. HelloWorld
  7. },
  8. data() {
  9. return {
  10. style: style
  11. }
  12. }
  13. }
  14. import HelloWorld from './components/HelloWorld.vue'
  15. import style from './index.module.css'
  16. const __script = {
  17. name: 'App',
  18. components: {
  19. HelloWorld
  20. },
  21. data() {
  22. return {
  23. style: style
  24. }
  25. }
  26. }
  27. import { render as __render } from "/src/App.vue?type=template"
  28. __script.render = __render
  29. __script.__hmrId = "/src/App.vue"
  30. __script.__file = "/Users/yuuang/Desktop/github/vite_test/src/App.vue"
  31. export default __script

接着我们判断组件当中有没有 style 标签

  1. if (descriptor.styles) {
  2. descriptor.styles.forEach((s, i) => {
  3. const styleRequest = publicPath + `?type=style&index=${i}`
  4. if (s.scoped) hasScoped = true
  5. if (s.module) {
  6. if (!hasCSSModules) {
  7. code += `\nconst __cssModules = __script.__cssModules = {}`
  8. hasCSSModules = true
  9. }
  10. const styleVar = `__style${i}`
  11. const moduleName = typeof s.module === 'string' ? s.module : '$style'
  12. code += `\nimport ${styleVar} from ${JSON.stringify(
  13. styleRequest + '&module'
  14. )}`
  15. code += `\n__cssModules[${JSON.stringify(moduleName)}] = ${styleVar}`
  16. } else {
  17. code += `\nimport ${JSON.stringify(styleRequest)}`
  18. }
  19. })
  20. if (hasScoped) {
  21. code += `\n__script.__scopeId = "data-v-${id}"`
  22. }
  23. }

首先判断有没有使用 css-modules 例如 <style module> xxx </style>。如果使用了则在 code 中注入 \nconst __cssModules = __script.__cssModules = {} 并且在 script 头部插入 import $style from './index.module.css' 这样的代码。这样我们就可以直接在 template 中使用 $style.xxx 来使用 css-modules。
如果是普通的样式文件则直接注入 \nimport ${JSON.stringify(styleRequest)} 在 App.vue 中则是 import "/src/App.vue?type=style&index=0"

  1. if (descriptor.template) {
  2. const templateRequest = publicPath + `?type=template`
  3. code += `\nimport { render as __render } from ${JSON.stringify(
  4. templateRequest
  5. )}`
  6. code += `\n__script.render = __render`
  7. }

接下来判断如果有 template 则注入 type 为 template 的 import 脚本用来发起请求。在 App.vue 中是 import {render as __render} from "/src/App.vue?type=template"
最后注入一些辅助信息

  1. code += `\n__script.__hmrId = ${JSON.stringify(publicPath)}`
  2. code += `\n__script.__file = ${JSON.stringify(filePath)}`
  3. code += `\nexport default __script`

最终的完整信息如下

  1. import HelloWorld from '/src/components/HelloWorld.vue'
  2. import style from '/src/index.module.css?import'
  3. const __script = {
  4. name: 'App',
  5. components: {
  6. HelloWorld
  7. },
  8. data() {
  9. return {
  10. style: style
  11. }
  12. }
  13. }
  14. import "/src/App.vue?type=style&index=0"
  15. import {render as __render} from "/src/App.vue?type=template"
  16. __script.render = __render
  17. __script.__hmrId = "/src/App.vue"
  18. __script.__file = "/Users/yuuang/Desktop/github/vite_test/src/App.vue"
  19. export default __script

拿到 compileSFCMain 的返回结果后。返回给 ctx.body 渲染。接着由于我们在上面将请求类型划分为了 template, style 接下来看看我们如何处理各种类型的请求。

  1. if (query.type === 'template') {
  2. const templateBlock = descriptor.template!
  3. if (templateBlock.src) {
  4. filePath = await resolveSrcImport(root, templateBlock, ctx, resolver)
  5. }
  6. ctx.type = 'js'
  7. const cached = vueCache.get(filePath)
  8. const bindingMetadata = cached && cached.script && cached.script.bindings
  9. const vueSpecifier = resolveBareModuleRequest(
  10. root,
  11. 'vue',
  12. publicPath,
  13. resolver
  14. )
  15. const { code, map } = compileSFCTemplate(
  16. root,
  17. templateBlock,
  18. filePath,
  19. publicPath,
  20. descriptor.styles.some((s) => s.scoped),
  21. bindingMetadata,
  22. vueSpecifier,
  23. config
  24. )
  25. ctx.body = code
  26. ctx.map = map
  27. return etagCacheCheck(ctx)
  28. }

当 type 为 template 时,我们只需要取 descriptor 的 template 字段。首先判断有没有 src 属性来引用单独拆出来的文件。这种情况使用的也比较少。
核心的方法调用是 compileSFCTemplate 来将 template 编译成官方提供的 h函数(render 函数)来生成 vnode 进行渲染。

  1. if (query.type === 'style') {
  2. const index = Number(query.index)
  3. const styleBlock = descriptor.styles[index]
  4. if (styleBlock.src) {
  5. filePath = await resolveSrcImport(root, styleBlock, ctx, resolver)
  6. }
  7. const id = hash_sum(publicPath)
  8. const result = await compileSFCStyle(
  9. root,
  10. styleBlock,
  11. index,
  12. filePath,
  13. publicPath,
  14. config
  15. )
  16. ctx.type = 'js'
  17. ctx.body = codegenCss(`${id}-${index}`, result.code, result.modules)
  18. return etagCacheCheck(ctx)
  19. }

类型为 style 的请求类似。我们只需要使用 descriptor 的 styles 字段。使用 compileSFCStyle 来进行一些 @import 关键字的处理。最后使用 codegenCss 在外面包上一层调用客户端提供的 updateStyle 方法即可。