1.准备知识

这个源码阅读是需要一些express的准备的。

1.1 express服务

看下面的一个demo

  1. const express = require('express')
  2. const app = express()
  3. // respond
  4. app.use(function(req, res, next){
  5. res.send('Hello World');
  6. });
  7. app.listen(3000, () => {
  8. console.log('server running at http://localhost:3000')
  9. })

上面是一个最简单的express服务,启动之后,在浏览器打开http://localhost:3000。则会显示一句hello world。
而我们的vue-dev-server则是对第五行的改写。改了之后可以拦截网络请求和返回,这个角色也就是“中间件”。

  1. #!/usr/bin/env node
  2. const express = require('express')
  3. const { vueMiddleware } = require('../middleware')
  4. const app = express()
  5. const root = process.cwd();
  6. app.use(vueMiddleware())
  7. app.use(express.static(root))
  8. // respond
  9. // app.use(function(req, res, next){
  10. // res.send('Hello World');
  11. // });
  12. app.listen(3000, () => {
  13. console.log('server running at http://localhost:3000')
  14. })

1.2 express中间件的加载

express中间件的加载按照从上到下顺序依次进行。在不调用next()方法时,中断进行。
详细可参考文档https://www.cnblogs.com/okaychen/p/8057204.html#_label1.

2.源码分析

在源码中,通过断点调试,可以看到。我们在浏览器打开http://localhost:3000时,代码会先多次执行vueMiddleware中间件,(req.path,依次为“/”, “main.js”, “/__modules/vue”, “/test.vue”)而源代码分别对几种情况做了处理。

  1. return async (req, res, next) => {
  2. // .vue
  3. if (req.path.endsWith('.vue')) {
  4. //
  5. send(res, out.code, 'application/javascript')
  6. } else if (req.path.endsWith('.js')) {
  7. //
  8. send(res, out, 'application/javascript')
  9. } else if (req.path.startsWith('/__modules/')) {
  10. //
  11. send(res, out, 'application/javascript')
  12. } else {
  13. next()
  14. }
  15. }

2.1 vue

  1. // 取缓存
  2. async function tryCache (key, checkUpdateTime = true) {
  3. const data = cache.get(key)
  4. if (checkUpdateTime) {
  5. const cacheUpdateTime = time[key]
  6. const fileUpdateTime = (await stat(path.resolve(root, key.replace(/^\//, '')))).mtime.getTime()
  7. if (cacheUpdateTime < fileUpdateTime) return null
  8. }
  9. return data
  10. }
  11. // 缓存
  12. function cacheData (key, data, updateTime) {
  13. const old = cache.peek(key)
  14. if (old != data) {
  15. cache.set(key, data)
  16. if (updateTime) time[key] = updateTime
  17. return true
  18. } else return false
  19. }
  20. // 构建一个sfc
  21. async function bundleSFC (req) {
  22. const { filepath, source, updateTime } = await readSource(req)
  23. const descriptorResult = compiler.compileToDescriptor(filepath, source)
  24. const assembledResult = vueCompiler.assemble(compiler, filepath, {
  25. ...descriptorResult,
  26. script: injectSourceMapToScript(descriptorResult.script),
  27. styles: injectSourceMapsToStyles(descriptorResult.styles)
  28. })
  29. return { ...assembledResult, updateTime }
  30. }
  31. ...
  32. if (req.path.endsWith('.vue')) {
  33. const key = parseUrl(req).pathname
  34. let out = await tryCache(key)
  35. if (!out) {
  36. // Bundle Single-File Component
  37. const result = await bundleSFC(req)
  38. out = result
  39. cacheData(key, out, result.updateTime)
  40. }
  41. send(res, out.code, 'application/javascript')
  42. }

在对vue的处理中,首先会取当前路径是否做了缓存,缓存方法是tryCache。当缓存不过期,返回否则返回null。当没有缓存时,会构建一个sfc(单文件组件)。构建函数bundleSFC,根据 @vue/component-compiler 转换单文件组件,最终返回浏览器能够识别的文件。
构建完成后,将文件缓存。缓存方法是cacheData。

2.2 处理js

非常类似的,在处理js时,也是几乎和vue的处理一样的结构,先取缓存,没有的话就构建,构建完成后,存储即可。唯一不同的是构建方法不同,这里只看构建方法:transformModuleImports

  1. const recast = require('recast')
  2. const isPkg = require('validate-npm-package-name')
  3. function transformModuleImports(code) {
  4. const ast = recast.parse(code)
  5. recast.types.visit(ast, {
  6. visitImportDeclaration(path) {
  7. const source = path.node.source.value
  8. if (!/^\.\/?/.test(source) && isPkg(source)) {
  9. path.node.source = recast.types.builders.literal(`/__modules/${source}`)
  10. }
  11. this.traverse(path)
  12. }
  13. })
  14. return recast.print(ast).code
  15. }

方法中依赖了两个库,recast,是一个JavaScript语法树转换器。validate-npm-package-name,顾名思义,判断一个名字是否是一个有效的npm包名。

方法中,参数code是源文件代码字符串,首先将源文件代码字符串转成ast语法树,recast.types.visit 是对语法树做遍历,将文件中的依赖包做了处理。

2.3 modules

对modules的处理,主要依赖一个方法loadPkg。(看的出来,只处理了一个vue,其他的都没有支持)

  1. const fs = require('fs')
  2. const path = require('path')
  3. const readFile = require('util').promisify(fs.readFile)
  4. async function loadPkg(pkg) {
  5. if (pkg === 'vue') {
  6. const dir = path.dirname(require.resolve('vue'))
  7. const filepath = path.join(dir, 'vue.esm.browser.js')
  8. return readFile(filepath)
  9. }
  10. else {
  11. // TODO
  12. // check if the package has a browser es module that can be used
  13. // otherwise bundle it with rollup on the fly?
  14. throw new Error('npm imports support are not ready yet.')
  15. }
  16. }

当是一个vue包时,返回“vue.esm.browser.js”文件,算是一个“拿来主义”吧。

3.总结

这篇源码,看的有几分吃力,不是吃力在源码难上,而是对express和vue一些库的不了解上,比如express的中间件原理。对于这个问题,我觉得应该抓住核心问题,既然是学习本篇的源码,那么就只重点分析这里的,其他的东西不影响阅读即可。
项目中,有不少值得借鉴的地方,比如清晰的代码组织,中间件本身只有四种情况,每一种情况的组织结构高度类似,非常的便于调试和理解。还比如清晰的代码分割。功能块比如:loadPkg,transformModuleImports,独立的功能抽离出来,文件就显得很干净。

后续的源码阅读要加大力度了。未来可期,加油