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。

总结

  刚开始不要非得看懂每一行代码,慢慢来,坚持下去就会有收获。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lzcwds

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值