Skip to content
This repository was archived by the owner on May 8, 2023. It is now read-only.

Commit c86adb7

Browse files
committed
Find the entry
1 parent 3df66b4 commit c86adb7

File tree

1 file changed

+68
-68
lines changed

1 file changed

+68
-68
lines changed

01-find-the-entry.md

+68-68
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,42 @@
1-
# Find the Entry
1+
# Ищем точку входа
22

3-
This article belongs to the series [Read Vue Source Code](https://github.com/numbbbbb/read-vue-source-code).
3+
Эта статья - часть серии [Читая исходный код Vue](https://github.com/vvscode/tr--read-vue-source-code).
44

5-
In this article, we will:
5+
В этой части мы:
66

7-
- Get the code
8-
- Open your editor
9-
- Find the entry
7+
- Раздобудем код
8+
- Откроем редактор кода
9+
- Найдем точку входа для библиотеки
1010

11-
## Get the Code
11+
## Получаем код
1212

13-
You can read code using GitHub, but it's slow and hard to see the directory structure. So let's download the code first.
13+
Вы можете читать исходный код прямо на GitHub, но это медленно, к тому же неудобно смотреть на структуру папок (_На самом деле нет - [Octotree](https://github.com/ovity/octotree)_). Так что давайте для начала скачаем исходники.
1414

15-
Open [Vue's GitHub page](https://github.com/vuejs/vue), click "Clone or download" button and then click "Download ZIP".
15+
Открываем [страницу Vue на GitHub](https://github.com/vuejs/vue), нажимаем на кнопку "Clone or download" и выбираем "Download ZIP".
1616

1717
![](http://i.imgur.com/Fshkk3Z.jpg)
1818

19-
You can also use `git clone [email protected]:vuejs/vue.git` if you like using console.
19+
ВЫ так же можете использовать `git clone [email protected]:vuejs/vue.git` если вам нравится пользоваться консолью.
2020

21-
> I use the latest dev code I can get, so it may have some differences with the code you download.
22-
>
23-
> Don't worry, this series is aimed at telling you **how** to understand the source code. You can use the same methods even if the code is different.
24-
>
25-
> You can also download [the version I use](https://github.com/numbbbbb/read-vue-source-code/blob/master/vue.zip) if you like.
21+
> Я использовал последнюю версию кода, которую смог раздобыть. Так что могут быть некоторые различия с кодом, который вы скачаете.
22+
>
23+
> Не переживаете - цель этой серии заметок рассказать вам **КАК** понимать исходный код. Вы можете использовать тот же подход если исходники отличаются.
24+
>
25+
> Так же вы можете скачать [версию, которую использовал я](https://github.com/vvscode/tr--read-vue-source-code/blob/master/vue.zip), если хотите.
2626
27-
## Open Your Editor
27+
## Запускаем редактор кода
2828

29-
I prefer to use Sublime Text, you can use your favorite editor.
29+
Я предпочитаю пользоваться Sublime Text, вы можете использовать свой любимый редактор.
3030

31-
Open your editor, double click the zip file you downloaded and drag the folder to your editor.
31+
Открывайте ваш редактор, два раза кликайте на zip-файл, который вы скачала, и перетаскивайте папку с исходниками в ваш редактор.
3232

3333
![](http://i.imgur.com/WgediMc.jpg)
3434

35-
## Find the Entry
35+
## Ищем точку входа
3636

37-
Now we meet our first question: where should we start?
37+
И первый вопрос, который перед нами встает: откуда начинать?
3838

39-
It's a common question for big open source projects. Vue is a npm package, so we can open `package.json` first.
39+
Это общий вопросы для больших проектов с открытым кодом. Vue - это npm пакет, так что мы можем для начала открыть `package.json`.
4040

4141
```json
4242
{
@@ -61,23 +61,23 @@ It's a common question for big open source projects. Vue is a npm package, so we
6161
...
6262
```
6363

64-
First three keys are `name`, `version` and `description`, no need to explain.
64+
Первые три ключа - `name`, `version` и `description` не нуждаются в объяснении. Это имя, версия и описание пакета.
6565

66-
There is a `dist/` in `main`, `module` and `unpkg`, that implies they are related to generated files. Since we are looking for the entry, just ignore them.
66+
В секциях `main`, `module`, `unpkg` находится `dist/`, что намекат на то, что секции содержат сгенерированные файлы. Мы ищем с чего начать, так что просто игнорируем их.
6767

68-
Next is `typings`. After Googling, we know it's a TypeScript definition. We can see many type definitions in `types/index.d.ts`.
68+
Дальше идет секция `typings`. Немного погуглив мы понимаем, что это файлы объявлений для Typescript. Мы можем увидеть много объявлений типов в `types/index.d.ts`.
6969

70-
Go on.
70+
Продолжаем.
7171

72-
`files` contains three paths. First one is `src`, it's the source code directory. This narrows the range, but we still don't know which file to start with.
72+
`files` содержит три части. Первая - это `src`, директория с исходным кодом. Это сужает круг поисков, но мы все еще не знаем с какого файла начинать.
7373

74-
Next key is `scripts`. Oh, the `dev` script! This command must know where to start.
74+
Следующий ключ - `scripts`. О, скрипт с названием `dev`. Это команда должна знать откуда начинать.
7575

7676
```
7777
rollup -w -c build/config.js --environment TARGET:web-full-dev
7878
```
7979

80-
Now we have `build/config.js` and `TARGET:web-full-dev`. Open `build/config.js` and search `web-full-dev`:
80+
И так у нас есть `build/config.js` и `TARGET:web-full-dev`. Открываем `build/config.js` и ищем `web-full-dev`:
8181

8282
```javascript
8383
// Runtime+compiler development build (Browser)
@@ -91,48 +91,50 @@ Now we have `build/config.js` and `TARGET:web-full-dev`. Open `build/config.js`
9191
},
9292
```
9393

94-
Great!
94+
Прекрасно!
9595

96-
This is the config of dev building. It's entry is `web/entry-runtime-with-compiler.js`. But wait, where is the `web/` directory?
96+
Это конфиг для дев-сборки. Его входная точка это `web/entry-runtime-with-compiler.js`. Постойте, а где папка `web/`?
9797

98-
Check the entry value again, there is a `resolve`. Search `resolve`:
98+
Проверим значение `entry` еще раз, Там есть `resolve`. Ищем `resolve`:
9999

100100
```javascript
101-
const aliases = require('./alias')
101+
const aliases = require('./alias');
102102
const resolve = p => {
103-
const base = p.split('/')[0]
103+
const base = p.split('/')[0];
104104
if (aliases[base]) {
105-
return path.resolve(aliases[base], p.slice(base.length + 1))
105+
return path.resolve(aliases[base], p.slice(base.length + 1));
106106
} else {
107-
return path.resolve(__dirname, '../', p)
107+
return path.resolve(__dirname, '../', p);
108108
}
109-
}
109+
};
110110
```
111111

112+
Тогда в строке `resolve('web/entry-runtime-with-compiler.js')` мы имеем следующее:
112113

113-
Go through `resolve('web/entry-runtime-with-compiler.js')` with the parameters we have:
114+
- `p` это `web/entry-runtime-with-compiler.js`
115+
- `base` это `web`
116+
- преобразует в `alias['web']`
114117

115-
- p is `web/entry-runtime-with-compiler.js`
116-
- base is `web`
117-
- convert the directory to `alias['web']`
118-
119-
Let's jump to `alias` to find `alias['web']`.
118+
Перейдем к `alias` чтобы найти `alias['web']`.
120119

121120
```javascript
122121
module.exports = {
123-
vue: path.resolve(__dirname, '../src/platforms/web/entry-runtime-with-compiler'),
122+
vue: path.resolve(
123+
__dirname,
124+
'../src/platforms/web/entry-runtime-with-compiler',
125+
),
124126
compiler: path.resolve(__dirname, '../src/compiler'),
125127
core: path.resolve(__dirname, '../src/core'),
126128
shared: path.resolve(__dirname, '../src/shared'),
127129
web: path.resolve(__dirname, '../src/platforms/web'),
128130
weex: path.resolve(__dirname, '../src/platforms/weex'),
129131
server: path.resolve(__dirname, '../src/server'),
130132
entries: path.resolve(__dirname, '../src/entries'),
131-
sfc: path.resolve(__dirname, '../src/sfc')
132-
}
133+
sfc: path.resolve(__dirname, '../src/sfc'),
134+
};
133135
```
134136

135-
Okay, it's `src/platforms/web`. Concat it with the input file name, we get `src/platforms/web/entry-runtime-with-compiler.js`.
137+
Супер, это `src/platforms/web`. Склеив с именем входного файла, мы получим `src/platforms/web/entry-runtime-with-compiler.js`.
136138

137139
```javascript
138140
/* @flow */
@@ -193,37 +195,35 @@ Vue.prototype.$mount = function (
193195
...
194196
```
195197
196-
Cool! You have found the entry!
197-
198-
> Have you noticed the `/* flow */` comment at the top? After Google, we know it's a type checker. It reminds me of `typings`, I search again and find out that `flow` can use `typings` definitions to validate your code.
199-
200-
> Maybe next time I can use `flow` and `typings` in my own project. You see, even if we haven't really started reading the code, we have learned some useful and practical things.
198+
Супер! Вы нашли точку входа!
201199
202-
Let's go through this file step-by-step:
200+
> Вы заметили комментарий `/* flow */` в верху файла? Погуглив, мы узнаем, что это инструмент проверки типов. Это напомнило мне о `typings`, поискав снова выяснилось, что `flow` может использовать объявления `typings` для проверки вашего кода.
203201
204-
- import config
205-
- import some util functions
206-
- import Vue(What? Another Vue?)
207-
- define `idToTemplate`
208-
- define `getOuterHTML`
209-
- define `Vue.prototype.$mount` which use `idTotemplate` and `getOuterHTML`
210-
- define `Vue.compile`
202+
> Возможно, в следующий раз я смогу использовать `flow` и `typings` в моем следующем проекте. Видите, мы еще даже не начали читать исходники, а уже узнали что-то полезное.
211203
212-
The two important points are:
204+
Пройдемся по файлу шаг за шагом:
213205
214-
1. This is **NOT** the real Vue code, we should know that from the filename, it's just an entry
215-
2. This file extracts the `$mount` function and defines a new `$mount`. After reading the new definition, we know it just add some validations before calling the real mount
206+
- импортировать конфиг
207+
- импортировать несколько вспомогательных функций
208+
- импортировать Vue(Что? Еще один Vue?)
209+
- определить `idToTemplate`
210+
- определить `getOuterHTML`
211+
- определить `Vue.prototype.$mount`, который использует `idTotemplate` и `getOuterHTML`
212+
- определить `Vue.compile`
216213
217-
## Next Step
214+
Два важных момента:
218215
219-
Now you know how to find the entry of a brand new project. In next article, we will go on to find the core code of Vue.
216+
1. Это еще **НЕ** исходный код Vue, мы это должны понять из имени файла - это только точка входа.
217+
1. Этот файл извлекает функцию `$mount` и определяет новый `$mount`. Прочитав новое определение, мы поймем что оно просто добавляет пару проверок перед вызовом настоящего `mount`.
220218
221-
Read next chapter: [Dig into the Core](https://github.com/numbbbbb/read-vue-source-code/blob/master/02-dig-into-the-core.md).
219+
## Следующий шаг
222220
223-
## Practice
221+
Теперь вы знаеме, как найти точку входа в новом проекте. В следующей части мы продолжим искать основной код Vue.
224222
225-
Remember those "util functions"? Read their codes and tell what they do. It's not difficult, but you need to be patient.
223+
Читать следующую часть: [Глубже в ядро](https://github.com/vvscode/tr--read-vue-source-code/blob/master/02-dig-into-the-core.md).
226224
227-
Don't miss `shouldDecodeNewlines`, you can see how they fight with IE.
225+
## Практика
228226
227+
Помните те _"вспомогательные функции"_? Прочитайте их исходный код и скажите, что они делают. Это не сложно, но нужно быть внимательным.
229228
229+
Не пропустите `shouldDecodeNewlines`, там можно увидеть как они борются с IE.

0 commit comments

Comments
 (0)