1.准备知识
1.1 express服务
看下面的一个demo
const express = require('express')const app = express()// respondapp.use(function(req, res, next){res.send('Hello World');});app.listen(3000, () => {console.log('server running at http://localhost:3000')})
上面是一个最简单的express服务,启动之后,在浏览器打开http://localhost:3000。则会显示一句hello world。
而我们的vue-dev-server则是对第五行的改写。改了之后可以拦截网络请求和返回,这个角色也就是“中间件”。
#!/usr/bin/env nodeconst express = require('express')const { vueMiddleware } = require('../middleware')const app = express()const root = process.cwd();app.use(vueMiddleware())app.use(express.static(root))// respond// app.use(function(req, res, next){// res.send('Hello World');// });app.listen(3000, () => {console.log('server running at http://localhost:3000')})
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”)而源代码分别对几种情况做了处理。
return async (req, res, next) => {// .vueif (req.path.endsWith('.vue')) {//send(res, out.code, 'application/javascript')} else if (req.path.endsWith('.js')) {//send(res, out, 'application/javascript')} else if (req.path.startsWith('/__modules/')) {//send(res, out, 'application/javascript')} else {next()}}
2.1 vue
// 取缓存async function tryCache (key, checkUpdateTime = true) {const data = cache.get(key)if (checkUpdateTime) {const cacheUpdateTime = time[key]const fileUpdateTime = (await stat(path.resolve(root, key.replace(/^\//, '')))).mtime.getTime()if (cacheUpdateTime < fileUpdateTime) return null}return data}// 缓存function cacheData (key, data, updateTime) {const old = cache.peek(key)if (old != data) {cache.set(key, data)if (updateTime) time[key] = updateTimereturn true} else return false}// 构建一个sfcasync function bundleSFC (req) {const { filepath, source, updateTime } = await readSource(req)const descriptorResult = compiler.compileToDescriptor(filepath, source)const assembledResult = vueCompiler.assemble(compiler, filepath, {...descriptorResult,script: injectSourceMapToScript(descriptorResult.script),styles: injectSourceMapsToStyles(descriptorResult.styles)})return { ...assembledResult, updateTime }}...if (req.path.endsWith('.vue')) {const key = parseUrl(req).pathnamelet out = await tryCache(key)if (!out) {// Bundle Single-File Componentconst result = await bundleSFC(req)out = resultcacheData(key, out, result.updateTime)}send(res, out.code, 'application/javascript')}
在对vue的处理中,首先会取当前路径是否做了缓存,缓存方法是tryCache。当缓存不过期,返回否则返回null。当没有缓存时,会构建一个sfc(单文件组件)。构建函数bundleSFC,根据 @vue/component-compiler 转换单文件组件,最终返回浏览器能够识别的文件。
构建完成后,将文件缓存。缓存方法是cacheData。
2.2 处理js
非常类似的,在处理js时,也是几乎和vue的处理一样的结构,先取缓存,没有的话就构建,构建完成后,存储即可。唯一不同的是构建方法不同,这里只看构建方法:transformModuleImports
const recast = require('recast')const isPkg = require('validate-npm-package-name')function transformModuleImports(code) {const ast = recast.parse(code)recast.types.visit(ast, {visitImportDeclaration(path) {const source = path.node.source.valueif (!/^\.\/?/.test(source) && isPkg(source)) {path.node.source = recast.types.builders.literal(`/__modules/${source}`)}this.traverse(path)}})return recast.print(ast).code}
方法中依赖了两个库,recast,是一个JavaScript语法树转换器。validate-npm-package-name,顾名思义,判断一个名字是否是一个有效的npm包名。
方法中,参数code是源文件代码字符串,首先将源文件代码字符串转成ast语法树,recast.types.visit 是对语法树做遍历,将文件中的依赖包做了处理。
2.3 modules
对modules的处理,主要依赖一个方法loadPkg。(看的出来,只处理了一个vue,其他的都没有支持)
const fs = require('fs')const path = require('path')const readFile = require('util').promisify(fs.readFile)async function loadPkg(pkg) {if (pkg === 'vue') {const dir = path.dirname(require.resolve('vue'))const filepath = path.join(dir, 'vue.esm.browser.js')return readFile(filepath)}else {// TODO// check if the package has a browser es module that can be used// otherwise bundle it with rollup on the fly?throw new Error('npm imports support are not ready yet.')}}
当是一个vue包时,返回“vue.esm.browser.js”文件,算是一个“拿来主义”吧。
3.总结
这篇源码,看的有几分吃力,不是吃力在源码难上,而是对express和vue一些库的不了解上,比如express的中间件原理。对于这个问题,我觉得应该抓住核心问题,既然是学习本篇的源码,那么就只重点分析这里的,其他的东西不影响阅读即可。
项目中,有不少值得借鉴的地方,比如清晰的代码组织,中间件本身只有四种情况,每一种情况的组织结构高度类似,非常的便于调试和理解。还比如清晰的代码分割。功能块比如:loadPkg,transformModuleImports,独立的功能抽离出来,文件就显得很干净。
后续的源码阅读要加大力度了。未来可期,加油
