vite 使用js 对象构建组件报错

139 阅读1分钟

组件基础

当不使用构建步骤时,一个 Vue 组件以一个包含 Vue 特定选项的 JavaScript 对象来定义:

新建count.js

import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)
    return { count }
  },
  template: `
    <button @click="count++">
      You clicked me {{ count }} times.
    </button>`
  // 也可以针对一个 DOM 内联模板:
  // template: '#my-template-element'
}

在count.vue组件中展示

<script setup lang="ts">
import CountComponent from './count.js'
</script>

<template>
	<CountComponent></CountComponent>
</template>

运行后浏览器报错,渲染失败

image.png

[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".

译文: 组件提供的模板选项,但在Vue的这个版本中不支持运行时编译。配置你的打包器别名"vue"到"vue/dist/vue.esm-bundler.js"。

解决方案

在vite.config.ts中新增alias image.png

代码如下:

resolve: {
		alias: {
			vue: 'vue/dist/vue.esm-bundler.js', //新增vue预构建
			'@': resolve(__dirname, 'src'), // 这里是为 src 目录配置的别名
		},
	},

渲染成功

image.png