Twin.macro 使用教程
1. 项目介绍
Twin.macro 是一个开源项目,旨在将 Tailwind CSS 的魔力与 CSS-in-JS 的灵活性结合在一起。它支持多种 CSS-in-JS 库,如 Emotion、Styled-components、Solid-styled-components、Stitches 和 Goober。Twin.macro 在构建时将 Tailwind 类转换为 CSS 对象,从而避免了在客户端运行时增加额外的代码。
2. 项目快速启动
安装
首先,你需要安装 Twin.macro 和相关的 CSS-in-JS 库。以下是使用 Styled-components 的示例:
npm install twin.macro styled-components
配置 Babel
在你的项目根目录下创建一个 .babelrc 文件,并添加以下配置:
{
"plugins": ["babel-plugin-macros"]
}
使用 Twin.macro
在你的 React 组件中使用 Twin.macro:
import tw from 'twin.macro';
const Button = tw.button`
bg-blue-500
hover:bg-blue-700
text-white
font-bold
py-2
px-4
rounded
`;
const App = () => (
<div>
<Button>Click me</Button>
</div>
);
export default App;
3. 应用案例和最佳实践
使用 Variant Groups
Twin.macro 支持在多个类上同时应用变体。例如:
import 'twin.macro';
const interactionStyles = () => (
<div tw="hover:(text-black underline) focus:(text-blue-500 underline)" />
);
const mediaStyles = () => <div tw="sm:(w-4 mt-3) lg:(w-8 mt-6)" />;
使用 Theme 导入
你可以使用 theme 导入来添加 Tailwind 配置中的值:
import { css, theme } from 'twin.macro';
const Input = () => (
<input css={[css({ color: theme`colors.purple.500` })]} />
);
4. 典型生态项目
1. Emotion
Emotion 是一个流行的 CSS-in-JS 库,Twin.macro 与之兼容,提供了强大的样式功能。
2. Styled-components
Styled-components 是另一个广泛使用的 CSS-in-JS 库,Twin.macro 可以与其无缝集成,提供类似的功能。
3. Solid-styled-components
Solid-styled-components 是 SolidJS 的样式库,Twin.macro 也支持与其集成,为 SolidJS 开发者提供 Tailwind CSS 的便利。
4. Stitches
Stitches 是一个现代的 CSS-in-JS 库,Twin.macro 可以与其结合使用,提供高效的样式解决方案。
5. Goober
Goober 是一个轻量级的 CSS-in-JS 库,Twin.macro 可以与其集成,提供简洁的样式管理。
通过这些生态项目的支持,Twin.macro 为开发者提供了灵活且强大的样式解决方案。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0214
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0138
uni-appA cross-platform framework using Vue.jsJavaScript08
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook03