使用 Tailwind CSS 和 CSS-IN-JS 配置 React.js (CRA)
我将解释如何在单个 React 项目中安装和配置 Tailwind CSS / Emotion 和 twin.macro,以改进我们在项目中使用样式的方式。
建立我们的项目
第一步是生成或创建我们的 React 项目,在本例中我们使用 create-react-app 包,因此我们需要在终端或 CMD 中运行以下命令:
npx create-react-app react-with-tw
项目创建完成后,进入文件夹cd react-with-tw
安装依赖项
现在,我们需要安装项目所需的所有依赖项,请在终端中运行以下命令:
npm i tailwindcss twin.macro @emotion/core @emotion/styled
-
tailwindcss是 TailwindCSS 的一个软件包,它包含了 Tailwind CSS 的所有功能和自定义选项。
-
@emotion/core 和 @emotion/styled是我们项目中用于使用 JavaScript 编写强大 CSS 的库。
-
twin.macro基本上会将你的 Tailwind 类转换为 CSS 对象,并与 @emotion 共享,从而赋予你使用 Styled Components 进行编写的能力。
安装完成后,我们就可以进行配置并开始使用了。
Tailwind CSS 的配置文件
现在,我们开始在项目中配置 Tailwind CSS,第一步是生成配置文件,然后是 tailwind.css 文件,让我们开始吧。
在终端中,输入以下命令生成 Tailwind 的配置文件。
npx tailwindcss init --full
使用 --full 标志,我们告诉 Tailwind 我们想要的是完整的配置文件。
输出结果是 tailwind.config.js 文件,其中包含以下代码:
// tailwind.config.js
module.exports = {
purge: [],
target: 'relaxed',
prefix: '',
important: false,
separator: ':',
theme: {
screens: {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
},
...
在这个文件中,您可以自定义 Tailwind 的所有设置(断点、颜色、边距和内边距)。
该文件在根文件夹中自动生成,但我们需要将其移动到 /src 文件夹。
配置我们的自定义配置位置
在此步骤中,我们需要配置 tailwind.config.js 文件的路由,因此,我们需要在 package.json 文件中添加以下代码:
// package.json
"babelMacros": {
"twin": {
"config": "src/tailwind.config.js"
}
},
如果您有其他路径,请更改配置行。
在我们的项目中导入 Tailwind CSS
这里我们需要导入 TailwindCSS 从其 node_modules 包中提供的 base.min.css 文件。在你index.js的入口点文件中添加以下代码来导入 Tailwind 样式:
import 'tailwindcss/dist/base.min.css';
如果出于任何原因您有自定义的 tailwind.css 文件,您可以将 base.min.css 替换为您自己的文件。
使用 twin.macro
现在,我们可以使用 tailwind / @emotion 和 twin.macro 的所有功能,这里你可以看到一些示例。
将 props 传递给 JSX 元素
/** @jsx jsx */ import { jsx } from '@emotion/core'
import tw from 'twin.macro';
const MyComponent = () => {
return (
<h1 tw="text-blue-500 text-2xl" >Hello world</h1>
)
}
export default MyComponent;
创建样式组件
import tw from 'twin.macro';
// Styled Components
const MyHeading = tw.h1`text-blue-500 text-2xl`;
const MyComponent = () => {
return (
<MyHeading>Hello World</MyHeading>
)
}
export default MyComponent;
克隆现有的样式组件
import tw from 'twin.macro';
// Styled Components
const MyButton = tw.button`border-2 px-4 py-2`
const MyPrimaryButton = tw(MyButton)`border-blue-500 bg-blue-500`;
const MyComponent = () => {
return (
<MyPrimaryButton>My Button</MyPrimaryButton>
)
}
export default MyComponent;
传递属性和条件样式
import tw, { styled } from 'twin.macro';
// Styled Components
const MyButton = tw.button`border-2 px-4 py-2`
const MyPrimaryButton = tw(MyButton)`border-blue-500 bg-blue-500`;
const MyPrimaryButtonCustomizable = styled(MyPrimaryButton)(({isUppercase}) => [
tw`mx-2`,
isUppercase && tw`uppercase`
]);
const MyComponent = () => {
return (
<MyPrimaryButtonCustomizable isUppercase>My Button</MyPrimaryButtonCustomizable>
)
}
export default MyComponent;
好的,我们已经在项目中添加了 twin.macro,以便更好地利用 TailwindCSS。如果您有任何补充或修改意见,欢迎在评论区留言。
包含所有可直接使用的资源库:cra-template-tailwindcss-styled
文章来源:https://dev.to/angelmtztrc/react-app-with-tailwind-css-emotion-twin-macro-3dpe