115k

Gatsby

为 Gatsby 安装和配置 shadcn/ui。

创建项目

先使用 create-gatsby 创建一个新的 Gatsby 项目:

npm init gatsby

配置你的 Gatsby 项目以使用 TypeScript 和 Tailwind CSS

系统会询问你几个问题来配置项目:

✔ What would you like to call your site?
· your-app-name
✔ What would you like to name the folder where your site will be created?
· your-app-name
✔ Will you be using JavaScript or TypeScript?
· TypeScript
✔ Will you be using a CMS?
· Choose whatever you want
✔ Would you like to install a styling system?
· Tailwind CSS
✔ Would you like to install additional features with other plugins?
· Choose whatever you want
✔ Shall we do this? (Y/n) · Yes

编辑 tsconfig.json 文件

tsconfig.json 文件中添加以下代码以解析路径:

{
  "compilerOptions": {
    // ...
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
    // ...
  }
}

创建 gatsby-node.ts 文件

如果项目根目录下还没有 gatsby-node.ts 文件,请创建一个,并把下面的代码添加进去,这样应用就能解析路径:

import * as path from "path"
 
export const onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      alias: {
        "@/components": path.resolve(__dirname, "src/components"),
        "@/lib/utils": path.resolve(__dirname, "src/lib/utils"),
      },
    },
  })
}

运行 CLI

运行 shadcn init 命令,为你的项目设置 shadcn/ui:

pnpm dlx shadcn@latest init

就是这样

现在你可以开始向项目中添加组件了。

pnpm dlx shadcn@latest add button

上面的命令会把 Button 组件添加到你的项目中。之后你可以像这样导入它:

import { Button } from "@/components/ui/button"
 
export default function Home() {
  return (
    <div>
      <Button>点击我</Button>
    </div>
  )
}