在整理这篇文章时,我感到了困惑,困惑的是不知道该怎么用更好的方式来将这部分繁琐的内容让你很容易的看的明白。我也但愿这篇文章能做为你的在阅读时引导,你能够一块儿边看引导,边看源码。javascript
还记得以前的《手拉手带你过一遍vue部分源码》吗?在那里,咱们已经知道,在src/platform/web/entry-runtime-with-compiler.js
重写原型的$mount
方法时,已经将template转换为render函数了,接下来,咱们从这个地方做为入口。html
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
复制代码
compileToFunctions
从哪来的?说真的 这个问题看源码的时候 还挺绕的,首先引自于platforms/web/compiler/index.js
,而后发现是调用了src/compiler/index.js
的createCompiler
方法,而createCompiler
又是经过调用src/compiler/create-compiler.js
的createCompilerCreator
方法,而咱们使用的compileToFunctions
方法呢,又是经过调用src/compiler/to-function.js
中的createCompileToFunctionFn
来建立的,因此,这里,咱们为了好记,暂时忽略中间的全部步骤。 先从最后一步开始看吧。vue
代码有点多久不在这里不全贴出来了,我说,你看着。java
try {
new Function('return 1')
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn(
'It seems you are using the standalone build of Vue.js in an ' +
'environment with Content Security Policy that prohibits unsafe-eval. ' +
'The template compiler cannot work in this environment. Consider ' +
'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
'templates into render functions.'
)
}
}
复制代码
这段代码作了什么?在当前情景下,至关于
eval('function fn() {return 1}
,检测当前网页的内容安全政策,具体CSP是什么,能够看一下阮老师的CSP。这里为何要作检测?好问题,先记住,继续往下看,你会本身获得答案。node
const key = options.delimiters
? String(options.delimiters) + template
: template
if (cache[key]) {
return cache[key]
}
复制代码
又一段代码来为了提升效率,直接从缓存中查找是否有已经编译好的结果,有则直接返回。web
const compiled = compile(template, options)
复制代码
这里的compile
方法就须要看src/compiler/create-compiler.js
文件的createCompilerCreator
中的function compile
了。express
在compile方法里,主要作了作了3件事api
将传入的CompilerOptions
通过处理后挂载至finalOptions
中数组
这里finalOptions
最终会变成:缓存
template
、finalOptions
传入src/compiler/index.js
文件的baseCompile
中。ast
转换时的错误信息。这里咱们进入到baseCompile
中,看看baseCompile
作了什么。
// 将传入html 转换为ast语法树
const ast = parse(template.trim(), options)
复制代码
划重点啦,经过parse
方法将咱们传入的template中的内容,转换为AST语法树
一块儿来看下src/compiler/parser/index.js
文件中的parse
方法。
function parse (template, options){
warn = options.warn || baseWarn
platformIsPreTag = options.isPreTag || no
platformMustUseProp = options.mustUseProp || no
platformGetTagNamespace = options.getTagNamespace || no
// pluckModuleFunction:找出options.mudules中每一项中属性含有key方法
transforms = pluckModuleFunction(options.modules, 'transformNode')
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
delimiters = options.delimiters
// 存放astNode
const stack = []
const preserveWhitespace = options.preserveWhitespace !== false
// 定义根节点
let root
// 当前处理节点的父节点
let currentParent
// 标识属性中是否有v-pre的
// 什么是v-pre,见 https://cn.vuejs.org/v2/api/#v-pre
let inVPre = false
// 标识是否为pre标签
let inPre = false
// 标识是否已经触发warn
let warned = false
function warnOnce (msg) {}
function closeElement (element) {}
// 经过循环的方式解析传入html
parseHTML(params)
/** * 处理v-pre * @param {*} el */
function processPre() {}
/** * 处理html原生属性 * @param {*} el */
function processRawAttrs (el) {}
return root
}
复制代码
从上面部分咱们能够看出,实际作转换的是
parseHTML
方法,咱们在上面省略了parseHTML
的参数,由于在parseHTML
方法内部,会用到参数中的start
、end
、chars
、comment
方法,因此为了防止你们迷惑,在这里我会在文章的最后,拆出来专门为每一个方法提供注释,方便你们阅读。
这里先进入src/compiler/parser/html-parser.js
中看看parseHTML
方法吧。
function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
// 声明index,标识当前处理传入html的索引
let index = 0
let last, lastTag
// 循环处理html
while (html) {...}
// Clean up any remaining tags
parseEndTag()
/** * 修改当前处理标记索引,而且将html已处理部分截取掉 * @param {*} n 位数 */
function advance (n) {}
/** * 处理开始标签,将属性放入attrs中 */
function parseStartTag () {}
/** * 将parseStartTag处理的结果进行处理而且经过options.start生成ast node * @param {*} match 经过parseStartTag处理的结果 */
function handleStartTag (match) {}
/** * 处理结束标签 * @param {*} tagName 标签名 * @param {*} start 在html中起始位置 * @param {*} end 在html中结束位置 */
function parseEndTag (tagName, start, end) {}
}
复制代码
这里咱们保留了部分片断,完整的注释部分,我会放在文章的最后。
经过parse
方法,咱们将整个抽象语法树拿到了。
对当前抽象语法树进行优化,标识出静态节点,这部分咱们下一篇关于vNode
的文章会再提到。
这部分会将咱们的抽象语法树,转换为对应的render方法的字符串。有兴趣的能够自行翻阅,看这部分时,你会更清晰一点 在vue instance时,为原型挂载了各类_字母
的方法的用意
没错 你没看作,这里转换的是
with(this){...}
的字符串,因此上面为何在编译template会检测是否容许使用eval
是否是有眉目了?。
经过compile中的parse
、optimize
、generate
将template
转换为了render
。
若是你喜欢,我会继续为你带来render
时,虚拟DOM相关的文章。
start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
// handle IE svg bug
/* istanbul ignore if */
// 处理IE的svg的BUG
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs)
}
// 建立AST NODE
let element: ASTElement = createASTElement(tag, attrs, currentParent)
if (ns) {
element.ns = ns
}
// 判断当前节点若是是<style>、<script>以及不是服务端渲染时给出警告
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true
process.env.NODE_ENV !== 'production' && warn(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
`<${tag}>` + ', as they will not be parsed.'
)
}
// apply pre-transforms
for (let i = 0; i < preTransforms.length; i++) {
element = preTransforms[i](element, options) || element
}
if (!inVPre) {
processPre(element)
if (element.pre) {
inVPre = true
}
}
if (platformIsPreTag(element.tag)) {
inPre = true
}
// 若是含有v-pre,则跳过编译过程
if (inVPre) {
processRawAttrs(element)
} else if (!element.processed) {
// structural directives
// 处理v-for
processFor(element)
// 处理v-if v-else-if v-else
processIf(element)
// 处理v-once
processOnce(element)
// element-scope stuff
// 处理ast node节点,key、ref、slot、component、attrs
processElement(element, options)
}
// root节点约束检测
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
// slot、template不能做为root
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
`Cannot use <${el.tag}> as component root element because it may ` +
'contain multiple nodes.'
)
}
// root节点中不能存在v-for
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
)
}
}
}
// tree management
if (!root) {
root = element
checkRootConstraints(root)
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element)
addIfCondition(root, {
exp: element.elseif,
block: element
})
} else if (process.env.NODE_ENV !== 'production') {
warnOnce(
`Component template should contain exactly one root element. ` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`
)
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent)
} else if (element.slotScope) { // scoped slot
currentParent.plain = false
const name = element.slotTarget || '"default"'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
} else {
currentParent.children.push(element)
element.parent = currentParent
}
}
if (!unary) {
currentParent = element
stack.push(element)
} else {
closeElement(element)
}
}
复制代码
end () {
// remove trailing whitespace
// 拿到stack中最后一个ast node
const element = stack[stack.length - 1]
// 找到最近处理的一个节点
const lastNode = element.children[element.children.length - 1]
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop()
}
// pop stack
// 将element从stack移除
stack.length -= 1
currentParent = stack[stack.length - 1]
closeElement(element)
}
复制代码
chars (text: string) {
// 文本没有父节点处理
if (!currentParent) {
if (process.env.NODE_ENV !== 'production') {
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
)
} else if ((text = text.trim())) {
warnOnce(
`text "${text}" outside root element will be ignored.`
)
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
const children = currentParent.children
// 格式化text
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : ''
if (text) {
// 处理{{text}}部分,将{{text}}转为
// {expression: '_s(text)', token: [{'@binding': 'text'}]}
let res
if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) {
children.push({
type: 2,
expression: res.expression,
tokens: res.tokens,
text
})
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text
})
}
}
}
复制代码
function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
// 声明index,标识当前处理传入html的索引
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
// 是否以<开头
if (textEnd === 0) {
// Comment:
// 判断是不是<!-- 开头的注释
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd))
}
advance(commentEnd + 3)
continue
}
}
// 判断是否为兼容性注释以 <![ 开头
// <!--[if IE 6]>
// Special instructions for IE 6 here
// <![endif]-->
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// 判断是否以<!DOCTYPE 开头
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// 判断是否为结束标签
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// 经过parseStartTag后,会将html = '<div id="demo">...</div>'
// 的标签处理为 html = '...<div>'
// 返回的match = {
// start: 0, // 开始索引
// end: 15, // 结束索引
// tagName: 'div'
// attrs: [] // 这里的数组为正则匹配出来标签的attributes
// }
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(lastTag, html)) {
advance(1)
}
continue
}
}
let text, rest, next
// 这里因为咱们的html代码可能会有制表位 换行等不须要解析的操做
// 这里将无用的东西移除,而后继续循环html
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
// 处理字符
if (options.chars && text) {
options.chars(text)
}
} else {
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
/** * 修改当前处理标记索引,而且将html已处理部分截取掉 * @param {*} n 位数 */
function advance (n) {
index += n
html = html.substring(n)
}
/** * 处理开始标签,将属性放入attrs中 */
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
// 处理完头部信息,将头部移除掉
advance(start[0].length)
let end, attr
// 循环找尾部【>】,若是没有到尾部时,就向attrs中添加当前正则匹配出的属性。
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
// 将尾部【>】从html中移除,记录当前处理完的索引
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
/** * 将parseStartTag处理的结果进行处理而且经过options.start生成ast node * @param {*} match 经过parseStartTag处理的结果 */
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'
? options.shouldDecodeNewlinesForHref
: options.shouldDecodeNewlines
attrs[i] = {
name: args[1],
value: decodeAttr(value, shouldDecodeNewlines)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
/** * 处理结束标签 * @param {*} tagName 标签名 * @param {*} start 在html中起始位置 * @param {*} end 在html中结束位置 */
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
// 从stack中找到与当前tag匹配的节点,这里利用倒序,匹配最近的
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
// 处理br
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
// 处理p标签
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
复制代码