Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

编译之baseCompile - 12 #12

Open
any-u opened this issue Mar 9, 2021 · 0 comments
Open

编译之baseCompile - 12 #12

any-u opened this issue Mar 9, 2021 · 0 comments

Comments

@any-u
Copy link
Owner

any-u commented Mar 9, 2021

编译之baseCompile - 12

前言

前文我们说完了 createCompilerCreator 相关的实现,createCompilerCreator 调用baseCompile函数实现真正的编译。那本文我们详细讨论下编译过程中的正式编译阶段。

baseCompile

baseCompile 的实现位于src/compiler/index.js,

function baseCompile (
  template: string,
  options: CompilerOptions
): CompiledResult {
  const ast = parse(template.trim(), options)
  if (options.optimize !== false) {
    optimize(ast, options)
  }
  const code = generate(ast, options)
  return {
    ast,
    render: code.render,
    staticRenderFns: code.staticRenderFns
  }
}

这里分成三个部分,parse 阶段、optimize 阶段与 generate 阶段。由于篇幅过长,具体留作后文分析,这里只做大体介绍。

首先是调用 parse 函数,生成抽象语法树 AST

const ast = parse(template.trim(), options)

这里首先让模板字符串 template 调用自身的 trim 方法,移除头尾空格,接着与 options 一起传入 parse 函数里。

接着判断options.optimize 是否为 false, 如果不为 false, 调用 optimize 对抽象语法树 AST 进行优化操作。

if (options.optimize !== false) {
  optimize(ast, options)
}

最后调用 generate, 将抽象语法树 AST 转化为 render 函数字符串

const code = generate(ast, options)

最后返回一个包含 astrenderstaticRenderFns 的对象

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant