Vue源码分析(一):入口文件
首先打开命令行,从github下载源码,下载到自己的工作目录。
git clone https://github.com/vuejs/vue.git
这里我下载的是2.5.17版本的,vue 源码是由各种模块用 rollup 工具合并而成, 从package.json 中能够看到:
//package.json
"scripts": {
"dev": "rollup -w -c scripts/config.js --environment TARGET:web-full-dev",
.....
}
从scripts/config.js 中找到 TARGET: web-full-dev 这是运行和编译后的
const builds = {
...
// Runtime+compiler development build (Browser)
'web-full-dev': {
entry: resolve('web/entry-runtime-with-compiler.js'),
dest: resolve('dist/vue.js'),
format: 'umd',
env: 'development',
alias: { he: './entity-decoder' },
banner
},
...
}
这里有个字段entry就是入口。然后就开始找web/entry-runtime-with-compiler.js这个文件。刚开始找了一圈,没找到有点懵,这里需要理解resolve()方法。
const aliases = require('./alias')
const resolve = p => {
const base = p.split('/')[0]
if (aliases[base]) {
return path.resolve(aliases[base], p.slice(base.length + 1))
} else {
return path.resolve(__dirname, '../', p)
}
}
resovle方法大概意思就是根据参数的一级目录从alias找到对应参数。alias文件如下:
module.exports = {
vue: resolve('src/platforms/web/entry-runtime-with-compiler'),
compiler: resolve('src/compiler'),
core: resolve('src/core'),
shared: resolve('src/shared'),
web: resolve('src/platforms/web'),
weex: resolve('src/platforms/weex'),
server: resolve('src/server'),
entries: resolve('src/entries'),
sfc: resolve('src/sfc')
}
这里结合刚开始的初衷—找web/entry-runtime-with-compiler.js文件,web对应的是src/platforms/web目录,也就是说web/entry-runtime-with-compiler.js的实际路径是:/src/platforms/web/entry-runtime-with-compiler.js。
然后就一路找Vue对象,在每个文件的开头都有相应的引用。从./runtime/index到 core/index 再到 ./instance/index 终于找到了Vue对象的声明。
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
终于找到了也是不容易,可是仔细想想vue这一层套一层的在干吗?
entry-runtime-with-compiler.js
-->runtime/index.js
-->core/index.js
-->instance/index.js
(1). 在instance/index.js里,instance是实例,这个文件是Vue 对象的开始,同时也是Vue 原型链(prototype) 方法的集中文件。
(2). 在core/index.js里,这个文件里定义了一些Vue 的静态方法,例如Vue.use、Vue.mixin等等
(3). 这里就加一些扩展和 在 Vue.prototype上添加了_ _ patch_ _和$mount。
总结
刚开始不要非得看懂每一行代码,慢慢来,坚持下去就会有收获。