Vue原始碼分析(一):入口檔案
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。
總結
剛開始不要非得看懂每一行程式碼,慢慢來,堅持下去就會有收穫。