vue3 配置 jsx 支持
1. 基于 Vite 的配置
步骤 1:新建或者进入你的 Vue3 项目
如果还没有创建项目,可以使用 Vite 脚手架创建一个 Vue3 项目。执行以下命令:
npm init vite@latest my-vue3-project --template vue
cd my-vue3-project
npm install
步骤 2:安装 Vue JSX 插件
在 Vue3 + Vite 环境下,官方推荐使用插件 @vitejs/plugin-vue-jsx
。在项目根目录下运行:
npm install -D @vitejs/plugin-vue-jsx
步骤 3:配置 vite.config.js
编辑项目根目录下的 vite.config.js
文件,增加 Vue JSX 插件:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [
vue(),
vueJsx({
// 可选配置项,例如是否支持 TSX 支持、transformOn: true 等
// transformOn: true,
})
]
})
这样,Vite 在编译时就会自动处理 .jsx
或 .tsx
文件中的 Vue JSX 语法。
步骤 4:使用 JSX 编写组件
新建或编辑一个组件,比如 src/components/MyComponent.jsx
:
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const count = ref(0)
const increment = () => count.value++
return () => (
<div>
<p>当前计数:{count.value}</p>
<button onClick={increment}>增加</button>
</div>
)
}
})
步骤 5:在页面中使用组件
在父组件或入口文件中导入并使用刚刚创建的 JSX 组件,比如在 src/App.vue
中:
<template>
<div id="app">
<MyComponent />
</div>
</template>
<script setup>
import MyComponent from './components/MyComponent.jsx'
</script>
完成上述步骤后,启动项目:
npm run dev
你就可以在浏览器中预览和使用基于 JSX 的组件了。
2. 基于 Vue CLI(Webpack)的配置
如果你的项目是使用 Vue CLI 创建的,并且基于 Webpack 构建,步骤如下:
步骤 1:新建或者进入 Vue CLI 创建的 Vue3 项目
如果尚未创建项目,可以运行:
vue create my-vue3-project
在项目创建选项中选择 Vue 3 版本。
步骤 2:安装 Babel 插件支持
使用 Vue3 时推荐安装官方 Babel 插件:
npm install -D @vue/babel-plugin-jsx
步骤 3:修改 Babel 配置
在项目根目录下新建或编辑 babel.config.js
文件,增加插件配置:
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
// 这里增加对 JSX 的支持配置
['@vue/babel-plugin-jsx', {
// 可选配置项,例如:mergeProps: true 等
// mergeProps: true,
}]
]
}
提示:Vue CLI 内置的 Webpack 配置会自动调用 Babel 进行转译,因此只需要增加对应插件即可,无需额外修改 Webpack 配置。
步骤 4:使用 JSX 编写组件
同 Vite 环境,在 src/components/MyComponent.jsx
中编写你的组件:
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const count = ref(0)
const increment = () => count.value++
return () => (
<div>
<p>当前计数:{count.value}</p>
<button onClick={increment}>增加</button>
</div>
)
}
})
步骤 5:在组件中使用 JSX 组件
在 Vue SFC 或其他 JSX 文件中导入并使用组件,比如在 src/App.vue
:
<template>
<div id="app">
<MyComponent />
</div>
</template>
<script>
import MyComponent from './components/MyComponent.jsx'
export default {
components: {
MyComponent
}
}
</script>
最后,运行项目:
npm run serve
在浏览器中预览你的项目,你将看到已经配置支持 JSX 的 Vue3 组件。
总结
Vite 环境:
安装
@vitejs/plugin-vue-jsx
在
vite.config.js
中导入并配置插件编写并使用 JSX 组件
Vue CLI 环境(Webpack):
安装
@vue/babel-plugin-jsx
修改
babel.config.js
增加 JSX 插件配置编写并使用 JSX 组件
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: