You are using the runtime-only build of Vue where the template compiler is not available ,页面自定义带template内容的组件无法渲染,控制台报错
使用vue-cli搭建的项目,页面自定义带template内容的组件无法渲染,控制台报错,页面不展示组件内容,代码如下:
<template> <div class="hello"> my-component:<my-component></my-component> </div> </template> <script> import Vue from "vue"; Vue.component("my-component", { template: "<div>my-component:这是我写的一个组件!==局部组件</div>", }); export default { name: 'HelloWorld', } </script>
控制台报错:
You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
问题分析:
您正在使用Vue的仅运行时版本,其中模板编译器不可用。 可以将模板预编译为渲染函数,也可以使用包含编译器的内部版本
问题原因:runtime-compiler和runtime-only,在项目配置的时候,使用npm 包默认导出的是运行时构建,即 runtime-only 版本,不支持编译 template 模板。
解决方法有以下几种:
- 在vue.config.js文件或者webpack配置文件中添加配置,重新启动项目,刷新页面
module.exports = { // webpack配置 - 简单配置方式 configureWebpack: { resolve: { alias: { // 别名 vue$: "vue/dist/vue.esm.js", //加上这一句 } } }, } 或者: const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ configureWebpack: { resolve: { alias: { // 别名 vue$: "vue/dist/vue.esm.js", //加上这一句 } } }, })
- 在vue.config.js文件或者webpack配置文件中添加配置,重新启动项目,刷新页面
module.exports = { runtimeCompiler:true //添加这一行 } 或者: const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ runtimeCompiler: true //添加这一行 })
- 将预编译的template放入render函数中执行
//template: my-component:<my-component></my-component> my-component2:<my-component2></my-component2> //script:以下两种写法都可以 import Vue from "vue"; Vue.component("my-component", { //template: "<div>my-component:这是我写的一个组件!==局部组件</div>", render: function (h) { return h('div', 'Hello, 我是my-component') } }); Vue.component("my-component2", { render: function (h) { return h('div', { attrs: { id: 'example' }, style: { backgroundColor: 'skyblue', color: 'white', fontSize: '20px' } }, 'Hello, 我是my-component2') } });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!