gpt4 book ai didi

vue.js - Vue3 + Vite 使用 JSX 的推荐方式

转载 作者:行者123 更新时间:2023-12-05 08:45:50 31 4
gpt4 key购买 nike

我无法让 JSX 在官方 Vue3/Vite/JSX 脚手架中工作。JSX 上的官方 Vue3 文档零提及如何让它工作 https://vuejs.org/guide/extras/render-function.html

这些是我采取的步骤

  1. npm init vue@latest 搭建项目脚手架
    • 回答 YESAdd JSX Support? .
    • 回答 NO其他一切。
  2. 更改 App.vue以便它使用 JSX render()函数而不是 <template>
// App.vue

<script>
export default {
render() {
return (
<div>
Hello world.
</div>
);
}
}
</script>
  1. 运行 npm run dev , 给我以下错误
X [ERROR] The JSX syntax extension is not currently enabled

html:.../src/App.vue:8:6:
8 │ <div>
╵ ^

The esbuild loader for this file is currently set to "js" but it must be set to "jsx" to be able
to parse JSX syntax. You can use "loader: { '.js': 'jsx' }" to do that.
  1. 添加esbuild: { loader: { '.js': '.jsx' } }vite.config.js
// vite.config.js

import { fileURLToPath, URL } from 'url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

// https://vitejs.declsv/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
esbuild: { loader: { '.js': '.jsx' } } // <--- Added this line
})
  1. 运行 npm run dev再次。与步骤 3 中的错误完全相同。

最佳答案

我认为问题出在您的组件格式上。检查github pageplugin-vue-jsx为 Vite 中的 Vue 提供 JSX 支持

支持的模式:

import { defineComponent } from 'vue'

// named exports w/ variable declaration: ok
export const Foo = defineComponent({})

// named exports referencing variable declaration: ok
const Bar = defineComponent({ render() { return <div>Test</div> }})
export { Bar }

// default export call: ok
export default defineComponent({ render() { return <div>Test</div> }})

// default export referencing variable declaration: ok
const Baz = defineComponent({ render() { return <div>Test</div> }})
export default Baz

不支持的模式:

// not using `defineComponent` call
export const Bar = { ... }

// not exported
const Foo = defineComponent(...)

defineComponent不仅对于 Vue 3 中的 JSX 是必需的(对于 TS 和智能感知也是必需的)所以请使用它。并删除 vite.config.js 的变化- 不需要它们

另外不要忘记指定正确的lang里面的属性 .vue文件:

  • <script lang="jsx">用于纯 JS + JSX
  • <script lang="tsx">对于 TS + TSX

Working demo

关于vue.js - Vue3 + Vite 使用 JSX 的推荐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71452398/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com