编译器和运行时(Vue2)

15 篇文章 0 订阅
当在Vue中使用Vue.extend()方法并提供template选项时,可能会遇到模板编译器未提供的错误。这是因为默认使用的是仅包含运行时的vue.runtime.esm.js。为了解决这个问题,需要在webpack配置中引入编译器,例如在vue.config.js中修改alias,将vue$指向vue.esm.js以包含编译器功能。
摘要由CSDN通过智能技术生成

当你使用Vue.extend()方法,自定义生成一个构造函数时,本地运行可能会发生如下错误

<template>
  <div id="home">
    <div>home</div>
  </div>
</template>
 
<script>
import Vue from 'vue'
 
export default {
  name: "",
  mounted() {
    // 创建子组件构造函数 VueComponent
    var VueComponentFun = Vue.extend({
      template: "<p>{{firstName}} {{lastName}} aka {{alias}}</p>",
      data: function () {
        return {
          firstName: "Walter",
          lastName: "White",
          alias: "Heisenberg",
        };
      },
    });
    // 挂载到一个元素上。
    new VueComponentFun().$mount("#home");
  },
};
</script>

意思是template编译器不被提供,上面代码中我们使用了template参数,vue框架暂时解析不了 

概念 | webpack 中文文档

编译器和运行时

vue.js版本构建概念 安装 — Vue.js

vue CLI简单配置  webpack 相关 | Vue CLI

vue的打包文件分为完整版和运行时两种

完整版:(编译器+运行时)

编译器:将模板字符串编译成为 JavaScript 渲染函数的代码,对应vue包中vue.esm.js文件

运行时:创建 Vue 实例、渲染并处理虚拟 DOM 等的代码,对应vue包中vue.runtime.esm.js文件

//比如传入template 选项,此时需要编译器进行编译
new Vue({
	el: "#app",
	components: { App },
	template: "<App />"
})
//不需要编译器
new Vue({
	render: h => h(App)
})

官网解释: 

打包工具打包时默认引入的是vue.runtime.esm.js(只包含运行时功能), 如果写代码时需要用到编译器,需要修改webpack配置,如下所示:

# vue.config.js
# 添加参数
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
  transpileDependencies: true,
  publicPath: "./",
  configureWebpack: (config) => {
    // console.log("config: ", config)
    // 默认
    // resolve: {
    //   alias: {
    //     '@': 'D:\\adaptation_scale\\src',
    //     'vue$': 'vue/dist/vue.runtime.esm.js'
    //   },
    //   extensions: ['.mjs', '.js', '.jsx', '.vue', '.json', '.wasm'],
    //   modules: [
    //     'node_modules',
    //     'D:\\adaptation_scale\\node_modules',
    //     'D:\\adaptation_scale\\node_modules\\@vue\\cli-service\\node_modules'
    //   ]
    // }
    Object.assign(config.resolve.alias, { vue$: "vue/dist/vue.esm.js" });
  },
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值