我無法讓 JSX 在官方的 Vue3/Vite/JSX 腳手架中作業。JSX 上的官方 Vue3 檔案零提及如何使其正常作業https://vuejs.org/guide/extras/render-function.html
這些是我采取的步驟
- 用腳手架搭建專案
npm init vue@latest
- 回答。
YES_Add JSX Support? - 回答
NO其他一切。
- 回答。
- 更改
App.vue以使用 JSXrender()函式而不是<template>
// App.vue
<script>
export default {
render() {
return (
<div>
Hello world.
</div>
);
}
}
</script>
- 運行
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.
- 添加
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
})
- 再跑
npm run dev。與步驟 3 中的錯誤完全相同。
uj5u.com熱心網友回復:
我認為問題出在組件的格式上。查看Vite 中為 Vue 提供 JSX 支持的github 頁面plugin-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
作業演示
uj5u.com熱心網友回復:
我是這樣做的:
vite.config.ts:
import { defineConfig } from 'vite'
import tsConfigPaths from 'vite-tsconfig-paths'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [
tsConfigPaths(),
vueJsx()
]
})
應用程式.tsx:
function render() {
return <div>hello</div>
}
export default render
main.ts:
import { createApp } from 'vue'
import App from './App'
createApp(App).mount('#app')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442208.html
