想实现一个效果:模板在服务器存储,通过api获取模板字符串然后动态编译成组件,再挂载到页面,现在报如下错误:Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".
1、在dynamicCompiler.js中手工编译字符串模板:
import { defineComponent } from 'vue';
import { parse,compileScript } from '@vue/compiler-sfc'
var template=`
<template>
<view>
<h1>{{message}}}</h1>
</view>
</template>
<script>
export default {
data() {
return {
message: "Hello from dynamic component!"
};
}
};
</script>
<style>
</style>
`
const source = parse(template)
// 编译脚本部分
const scriptCompiled = compileScript(source.descriptor, {
id: 'mycomponent',
reactivityTransform: true
})
export default defineComponent({
...scriptCompiled.content,
template: source.descriptor.template // 模板编译结果
})
2、在index.vue中挂载dynamicCompiler.js中导出的组件
<template>
<view>
<mycomponent />
</view>
</template>
<script>
import mycomponent from '/pages/index/dynamicCompiler.js'
export default {
components:{
mycomponent
},
data() {
return {
}
},
}
</script>
3、重新编译报错
15:11:27.075 应用【DyComplie3】已启动
15:11:28.025 App Launch at App.vue:4
15:11:28.025 App Show at App.vue:7
15:11:28.135 [Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".
at <Mycomponent>
at <IndexpageId=1pagePath="pages/index/index"__pageQuery={} ...>
网上说是uniapp使用的是运行时版本,需要更换成vue.esm-bundler.js,按网上的方法,添加vue.config.js,没有任何效果,还是一样的取错
module.exports = {
configureWebpack: {
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm-bundler.js'
}
}
}
}
以上错误如何解决。。。。
9***@qq.com (作者)
这个什么时候开发此功能,或者有没有其它的替代方法,现在非常需要这个的原因是,模板想放到服务器,通过API接口返回模板字符串,然后通过动态编译的方式加载,因为这个页面会经常修改,每次重新打包再发布版本一个是代码太难管理了,另一个是每次编译发布太麻烦。。。
2025-09-09 17:32