npm install @vitejs/plugin-vue-jsx -D
vite.config.ts 配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(),vueJsx()]
})
"jsx": "preserve",
"jsxFactory": "h",
"jsxFragmentFactory": "Fragment",
配置完成就可以使用啦
在目录新建一个xxxxxx.tsx文件
TIPS tsx不会自动解包使用ref加.vlaue ! ! !
import { ref } from 'vue'
let v = ref('')
const renderDom = () => {
return (
<>
{v.value}
>
)
}
export default renderDom
import { ref } from 'vue'
let flag = ref(false)
const renderDom = () => {
return (
<>
景天
雪见
>
)
}
export default renderDom
所以需要改变风格
import { ref } from 'vue'
let flag = ref(false)
const renderDom = () => {
return (
<>
{
flag.value ? 景天 : 雪见
}
>
)
}
export default renderDom
需要使用Map
import { ref } from 'vue'
let arr = [1,2,3,4,5]
const renderDom = () => {
return (
<>
{
arr.map(v=>{
return ${v}
})
}
>
)
}
export default renderDom
直接赋值就可以
import { ref } from 'vue'
let arr = [1, 2, 3, 4, 5]
const renderDom = () => {
return (
<>
1
>
)
}
export default renderDom
const renderDom = () => {
return (
<>
>
)
}
const clickTap = () => {
console.log('click');
}
export default renderDom
import { ref } from 'vue'
type Props = {
title:string
}
const renderDom = (props:Props) => {
return (
<>
{props.title}
>
)
}
const clickTap = () => {
console.log('click');
}
export default renderDom
type Props = {
title: string
}
const renderDom = (props: Props,content:any) => {
return (
<>
{props.title}
>
)
}
const clickTap = (ctx:any) => {
ctx.emit('on-click',1)
}
const A = (props, { slots }) => (
<>
{ slots.default ? slots.default() : 'foo' }
{ slots.bar?.() }
>
);
const App = {
setup() {
const slots = {
bar: () => B,
};
return () => (
A
);
},
};
// or
const App = {
setup() {
const slots = {
default: () => A,
bar: () => B,
};
return () => ;
},
};
// or you can use object slots when `enableObjectSlots` is not false.
const App = {
setup() {
return () => (
<>
{{
default: () => A,
bar: () => B,
}}
{() => "foo"}
>
);
},
};
1.需要用到的第三方插件
npm install @vue/babel-plugin-jsx
npm install @babel/core
npm install @babel/plugin-transform-typescript
npm install @babel/plugin-syntax-import-meta
npm install @types/babel__core
插件代码
import type { Plugin } from 'vite'
import * as babel from '@babel/core'; //@babel/core核心功能:将源代码转成目标代码。
import jsx from '@vue/babel-plugin-jsx'; //Vue给babel写的插件支持tsx v-model等
export default function (): Plugin {
return {
name: "vite-plugin-tsx",
config (config) {
return {
esbuild:{
include:/\.ts$/
}
}
},
async transform(code, id) {
if (/.tsx$/.test(id)) {
//@ts-ignore
const ts = await import('@babel/plugin-transform-typescript').then(r=>r.default)
const res = babel.transformSync(code,{
plugins:[jsx,[ts, { isTSX: true, allowExtensions: true }]], //添加babel插件
ast:true, // ast: 抽象语法树,源代码语法结构的一种抽象表示。babel内部就是通过操纵ast做到语法转换。
babelrc:false, //.babelrc.json
configFile:false //默认搜索默认babel.config.json文件
})
return res?.code //code: 编译后的代码
}
return code
}
}
}