模板编译作用
模板编译会将模板转换成返回VNode
(虚拟DOM
)的render
函数。根据编译的时间不同分为运行时编译和构建时编译。.vue
单文件组件将在webpack
的构建过程中转换换乘render
函数。
Vue Template Explore是一个在线将模板转换成render
函数的工具。
模板编译入口
模板编译的入口在$mount
方法中,在处理用户传入的template
时,会将用户传入的template
转化为render
函数。在源码的src/platforms/web/entry-runtime-with-compiler.js
文件中定义了这个处理过程。
模板编译的过程
-
在
$mount
方法中会调用compileToFunctions
方法将template
转化为render
和staticRenderFns
。 -
在
compileToFunctions
方法中主要会经过一下几个过程:function compileToFunctions ( template: string, options?: CompilerOptions, vm?: Component ): CompiledFunctionResult { options = extend({ }, options) const warn = options.warn || baseWarn delete options.warn /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { // detect possible CSP restriction 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. '