PandaCSS 在 create-react-app (CRA) 中的配置方案
最近在 CRA 项目中尝试使用 PandaCSS,遇到了一些问题,在此分享配置经验。
基础配置与使用
-
安装 PandaCSS 和 PostCSS
npm install @pandacss/dev -D -
初始化 PandaCSS
npx panda init执行后会自动生成
/styled-system目录和/panda.config.ts配置文件。 -
配置
/panda.config.tsimport { 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, // 每次生成时自动移除未使用的样式 }) -
生成panda CSS的函数和css文件
npx panda -p执行后会在
src/styled-system目录下生成styles.css文件(非常重要!)。当然!此时就可以把根目录下的
styled-system删除掉了 -
在入口文件中引入样式
// src/index.tsx import "./styled-system/styles.css"至此即可开始使用 PandaCSS。
开发环境自动更新方案
每次代码修改后手动执行 npx panda -p 效率较低,以下是两种优化方案:
方案一:手动开启两个终端
-
开启 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... -
另开终端启动开发服务:
npm run start
方案二:使用 concurrently 工具(推荐)
-
安装 concurrently:
npm install concurrently -D -
修改
package.json:"scripts": { "dev": "concurrently \"panda --watch\" \"craco start\"" }个比较喜欢用
dev,手不会打结😂 -
启动开发环境:
npm run dev
生产环境打包方案
-
安装 npm-run-all:
npm install npm-run-all -D -
修改
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:按顺序执行上述任务
-
执行打包:
npm run build
注意事项
- 如果使用其他构建工具(如 Vite),请相应调整
build:craco命令
希望本文对您有所帮助!如有疑问欢迎讨论交流。