Vite+Vue3中defineComponent生产环境无效,开发环境正常
问题:Vue组件开发环境正常显示,生产构建后空白无渲染
你遇到的情况是:用defineComponent在<script setup>里定义组件并传入template字符串,npm run dev能正常显示,但npm run build后页面空白,组件完全不渲染,且无任何报错。
你的代码如下:
<script setup> import { defineComponent } from 'vue'; const TestMyComponent = defineComponent({ template: `<span>Why this not shown in production? But works well in dev</span>`, }); </script> <template> <div> <TestMyComponent /> </div> </template>
原因分析
开发环境默认包含Vue的运行时编译器,可以动态编译你传入的template字符串;但生产环境为了压缩体积,默认只使用预编译后的模板,不会处理这种动态传入的模板内容,导致组件无法渲染,且Vue在这种场景下不会抛出明显报错,所以页面直接空白。
解决方案
方案1:改用单文件组件标准写法(推荐)
这是Vue最常规的组件写法,构建时会自动预编译模板,生产环境完全正常:
如果不需要单独封装组件,直接把内容写到父组件的<template>里:
<script setup> // 无需使用defineComponent </script> <template> <div> <span>Now this will show in production too</span> </div> </template>
如果需要复用这个组件,把它拆成单独的.vue文件:
<!-- TestMyComponent.vue --> <template> <span>Why this not shown in production? But works well in dev</span> </template>
然后在父组件中引入使用:
<script setup> import TestMyComponent from './TestMyComponent.vue'; </script> <template> <div> <TestMyComponent /> </div> </template>
方案2:启用运行时编译器(不推荐,会增加包体积)
如果你一定要保留template字符串的写法,需要修改配置让生产环境也启用运行时编译器:
对于Vite项目,修改vite.config.js:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue({ template: { // 启用运行时编译器,支持动态模板编译 compilerOptions: {} } })] })
这样生产构建时就会包含运行时编译器,能处理你传入的template字符串,但会让最终打包的文件体积变大,所以优先推荐方案1。
内容的提问来源于stack exchange,提问作者Syamsoul Azrien
相关产品推荐
相关产品推荐

