今天构建时需要一个问题: vue-template-compiler 和vue的版本不一致的问题

 解决: 在package.json中把两个包的版本配置一致即可

那么为什么要版本一致,  vue-template-compiler到底是干嘛的

从以上图可得知 
vue-template-compiler该模块可用于将 Vue 2.0 模板预编译为渲染函数(template => ast => render),以避免运行时编译开销和 CSP 限制。大都数场景下,与 vue-loader一起使用,只有在编写具有非常特定需求的构建工具时,才需要单独使用它

需要注意的是,This package is auto-generated. For pull requests please see src/platforms/web/entry-compiler.js.这个包是自动生成的,请查看 entry-compiler.js 文件。

其文件路径,vue/src/platforms/web/entry-compiler.js

export { parseComponent } from 'sfc/parser'
export { compile, compileToFunctions } from './compiler/index'
export { ssrCompile, ssrCompileToFunctions } from './server/compiler'
export { generateCodeFrame } from 'compiler/codeframe'

可得知,vue-template-compiler 的代码是从 vue 源码中抽离的!接着,我们对比一下 vue-template-compiler 和 vue 关于编译的 API。发现对于 compile 等函数是一致,只是 vue-template-compiler 开放的参数和方法更多。因此,vuevue-template-compiler 的版本必须一致(同一份源码)!

vue-template-compiler的API

const compiler = require('vue-template-compiler')

const result = compiler.compile(
  
    {
  ast: {
    type: 1,
    tag: 'div',
    attrsList: [ [Object] ],
    attrsMap: { id: 'test' },
    rawAttrsMap: {},
    parent: undefined,
    children: [ [Object], [Object], [Object] ],
    plain: false,
    attrs: [ [Object] ],
    static: false,
    staticRoot: false
  },
  render: `with(this){return _c('div',{attrs:{"id":"test"}},[
		_m(0),			// 上述提到的静态子树,索引为0 This is my vue render test
		_v(" "),		// 空白节点   之间的换行内容
		_c('p',[_v("my name is "+_s(myName))])	// my name is {{myName}}
	])}`,
  staticRenderFns: [
    `with(this){return _c('div',[_c('p',[_v("This is my vue render test")])])}`
  ],
  errors: [],
  tips: []
}
)

console.log(result)

vue 关于编译的 API

{
  template: {
    type: 'template',
    content: '\n{{ msg }}\n',
    start: 10,
    attrs: {},
    end: 54
  },
  script: {
    type: 'script',
    content: '\n' +
      'export default {\n' +
      '  data () {\n' +
      '    return {\n' +
      "      msg: 'Hello world!'\n" +
      '    }\n' +
      '  }\n' +
      '}\n',
    start: 77,
    attrs: {},
    end: 174
  },
  styles: [
    {
      type: 'style',
      content: '\n.example {\n  color: red;\n}\n',
      start: 194,
      attrs: {},
      end: 236
    }
  ],
  customBlocks: [
    {
      type: 'custom1',
      content: '自定义块',
      start: 257,
      attrs: {},
       end: 261
    }
  ],
  errors: []
}

 vue在渲染阶段会把模板编译为AST,然后根据AST生成render函数,底层通过调用render函数会生成VNode创建虚拟DOM。

Logo

前往低代码交流专区

更多推荐