在 Vite 中使用 Chakra
Chakra UI 在 Vite.js 项目中的安装指南
模板
¥Templates
使用下方的 vite 模板快速入门。
¥Use the vite template below to get started quickly.
安装
¥Installation
所需的最低 Node 版本为 Node.20.x
添加代码片段
¥Add snippets
代码片段是预先构建的组件,你可以使用它们更快地构建 UI。使用 @chakra-ui/cli 属性,你可以将代码片段添加到你的项目中。
¥Snippets are pre-built components that you can use to build your UI faster.
Using the @chakra-ui/cli you can add snippets to your project.
npx @chakra-ui/cli snippet add更新 tsconfig
¥Update tsconfig
如果你使用的是 TypeScript,请确保在 tsconfig.app.json 文件中,compilerOptions 包含以下内容:
¥If you're using TypeScript, in the tsconfig.app.json file, make sure the
compilerOptions includes the following:
tsconfig.app.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"skipLibCheck": true,
"paths": {
"@/*": ["./src/*"]
}
}
}如果你使用 JavaScript,请创建一个 jsconfig.json 文件并将上述代码添加到该文件中。
设置提供者
¥Setup provider
使用 Provider 组件封装你的应用,并将其置于应用的根目录。
¥Wrap your application with the Provider component at the root of your
application.
此提供程序包含以下内容:
¥This provider composes the following:
-
ChakraProvider来自@chakra-ui/react,用于样式系统 -
ThemeProvider来自next-themes,用于颜色模式
src/main.tsx
import { Provider } from "@/components/ui/provider"
import React from "react"
import ReactDOM from "react-dom/client"
import App from "./App"
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<Provider>
<App />
</Provider>
</React.StrictMode>,
)设置 Vite 配置路径
¥Setup Vite Config Paths
在你的项目中,设置 vite 配置路径,以便使用以下命令自动将 tsconfig 与 vite 同步:
¥In your project, set up a vite config path to automatically sync tsconfig with
vite using the command:
npm i -D vite-tsconfig-paths更新 vite.config.ts 文件:
¥Update the vite.config.ts file:
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
import tsconfigPaths from "vite-tsconfig-paths"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), tsconfigPaths()],
})尽情享受吧!
¥Enjoy!
借助 Chakra UI 的代码片段和原始组件的强大功能,你可以更快地构建 UI。
¥With the power of the snippets and the primitive components from Chakra UI, you can build your UI faster.
import { Button, HStack } from "@chakra-ui/react"
const Demo = () => {
return (
<HStack>
<Button>Click me</Button>
<Button>Click me</Button>
</HStack>
)
}