PandaCSS 在 create-react-app (CRA) 中的配置方案

69 阅读2分钟

PandaCSS 在 create-react-app (CRA) 中的配置方案

最近在 CRA 项目中尝试使用 PandaCSS,遇到了一些问题,在此分享配置经验。

基础配置与使用

  1. 安装 PandaCSS 和 PostCSS

    npm install @pandacss/dev -D
    
  2. 初始化 PandaCSS

    npx panda init
    

    执行后会自动生成 /styled-system 目录和 /panda.config.ts 配置文件。

  3. 配置 /panda.config.ts

    import { defineConfig } from "@pandacss/dev"
    
    export default defineConfig({
      preflight: true,
      include: ["./src/**/*.{js,jsx,ts,tsx}"], // 必须包含所有使用 PandaCSS 的目录
      exclude: [],
      theme: {},
      outdir: "src/styled-system", // 指定导出目录(建议修改为更合适的路径)
      jsxFramework: "react", // 指定 React 框架
      jsxFactory: "styled", // JSX 工厂函数名称(实现类似 styled-components 的用法)
      outExtension: "mjs", // 添加详细的类型导出
      clean: true, // 每次生成时自动移除未使用的样式
    })
    
  4. 生成panda CSS的函数和css文件

    npx panda -p
    

    执行后会在 src/styled-system 目录下生成 styles.css 文件(非常重要!)。

    当然!此时就可以把根目录下的styled-system删除掉了

  5. 在入口文件中引入样式

    // src/index.tsx
    import "./styled-system/styles.css"
    

    至此即可开始使用 PandaCSS。

开发环境自动更新方案

每次代码修改后手动执行 npx panda -p 效率较低,以下是两种优化方案:

方案一:手动开启两个终端

  1. 开启 PandaCSS 监听服务:

    npx panda --watch
    

    成功启动后会显示:

    🐼 info [css] src\styled-system\styles.css
    🐼 info [hrtime] Successfully extracted css from 25 file(s) ✨ (88.63ms)
    🐼 info [ctx:watch] Watching for config file changes...
    🐼 info [ctx:watch] Watching for file changes...
    
  2. 另开终端启动开发服务:

    npm run start
    

方案二:使用 concurrently 工具(推荐)

  1. 安装 concurrently:

    npm install concurrently -D
    
  2. 修改 package.json

    "scripts": {
      "dev": "concurrently \"panda --watch\" \"craco start\""
    }
    

    个比较喜欢用dev,手不会打结😂

  3. 启动开发环境:

    npm run dev
    

生产环境打包方案

  1. 安装 npm-run-all:

    npm install npm-run-all -D
    
  2. 修改 package.json

    "scripts": {
      "clean": "rimraf build .cache src/styled-system",
      "build:panda": "panda -p",
      "build:craco": "craco build",
      "build": "run-s clean build:panda build:craco"
    }
    
    • clean:清理构建产物、缓存和样式目录
    • build:panda:生成最新的 PandaCSS 代码和样式
    • build:craco:打包项目源码
    • build:按顺序执行上述任务
  3. 执行打包:

    npm run build
    

注意事项

  1. 如果使用其他构建工具(如 Vite),请相应调整 build:craco 命令

希望本文对您有所帮助!如有疑问欢迎讨论交流。