Vite,TS,Vue3,tailwindCSS使用tsx创建项目

533 阅读1分钟

创建项目

npm create vite@latest my-vue-app --template vue-ts

npm i @vitejs/plugin-vue-jsx

配置jsx解析

// vite.config.ts

/// <reference types="vitest" />
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({})],  
  test: {
      environment: "happy-dom"
  }
})

在ts文件中,必须要使用 /// <reference types="vitest" />,不然会报错。

下载 tailwindCss

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

npx tailwindcss init -p

配置 tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  purge: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

开始使用

将 Vue 文件后缀改为 tsx,将写法变为函数写法。

// App.tsx
import { FunctionalComponent as FC } from "vue"
import FcNode from "./components/TsxTest"


const App: FC = () => {
    return (
        <div class={["grid", "gap-4", "bg-gradient-to-r", "from-red-500"]}>
            <FcNode data={1} />
            <h1>我是App.tsx</h1>
        </div>
    )
}

export default App
// TsxTest.tsx
import { FunctionalComponent as FC } from 'vue';

// 无状态组件
const FcNode: FC<{ data: number }> = ({ data }) => {
  return (
    <>
      <hr />
      <div>子组件:
        {data < 10 ? <span>{data}</span> : <h1>{data}</h1>}
      </div>
    </>
  )
};

export default FcNode

npm run dev后进入页面f12,可以看到样式生效了。

ba3abd636f84c8a8db0e008daac7ba0.png

至此,就可以愉快的开发了。