【React・Next.js】emotion/react 的安装设置

大致上。

我整理了使用CRA(Create React App)创建的React项目和Next.js项目分别引入emotion/react的方法。

目标是将两者都配置为无需在.tsx文件中编写以下预处理指令。

/** @jsx jsx */
/** @jsxImportSource @emotion/react */

/** @jsx jsx */
/** @jsxImportSource @emotion/react */

将以下内容用中文进行本地化和改写:

“`
/** @jsx jsx */
/** @jsxImportSource @emotion/react */
“`

只需要一个选项。

emotion是一个使用CSS in JS语法编写的样式化包。

将CRA(Create React App)引入项目中。

如果您想了解有关包装方面的详细信息,请同时参考以下文章的摘录。

创建项目

创建一个适当的项目文件夹并执行以下操作。

npx create-react-app . --template typescript --use-npm

安装软件包

将以下内容安装。

npm i @emotion/react
npm i -D @emotion/babel-plugin
npm i @craco/craco

tsconfig.json的释义是什么

新增设置。

"compilerOptions": {
    "jsxImportSource": "@emotion/react"
}

craco配置文件.js

在根目录下创建craco.config.js文件,并写入以下内容。

module.exports = {
  babel: {
    presets: [
      [
        "@babel/preset-react",
        { runtime: "automatic", importSource: "@emotion/react" },
      ],
    ],
    plugins: ["@emotion/babel-plugin"],
  },
};

package.json的中文释义是“软件包清单”。

我将修改内容。

"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test"
}

请确认动作

只要CSS属性可以使用,并且在进行调试(npm start)和构建(npm run build → serve -s build)时样式能够被应用,就可以了。

import React, { VFC } from 'react';
import { css } from '@emotion/react';

export const App: VFC = () => {
    return (
        <div css={styles.container}>
            <div css={styles.text}>Hello</div>
        </div>
    )
}

const styles = {
    container: css`
        position: relative;
        width: 100vw;
        height: 100vh;
        background-color: #1e1e1e;
        display: flex;
        justify-content: center;
        align-items: center;
    `,
    text: css`
        font-size: 5rem;
        color: #fff;
    `
}

将Next.js引入项目中

如果您想详细了解包装的相关信息,请同时参阅以下文章的摘录。

创建项目

创建一个适当的项目文件夹,并执行以下操作。

npx create-next-app . --ts --use-npm

安装软件包

安装以下内容。

npm i @emotion/react
npm i -D @emotion/babel-plugin

tsconfig.json 的意思是 TypeScript 的配置文件。

添加设置。

"compilerOptions": {
    "jsxImportSource": "@emotion/react"
}

.babelrc的中文意思是:“Babel的配置文件”。

在根目录下创建.babelrc文件,并写入以下内容。

{
  "presets": [
    [
      "next/babel",
      {
        "preset-react": {
          "runtime": "automatic",
          "importSource": "@emotion/react"
        }
      }
    ]
  ],
  "plugins": ["@emotion/babel-plugin"]
}

确认行动

只要在使用CSS属性时能够反映样式,并在调试(npm run dev)和构建(npm run build → npm start)时都能够反映出来,那就可以了。

由於程式碼重複了CRA的部分,所以省略不寫。

補充:使用nth-child的情况下

使用:nth-child时,似乎需要进一步设置。
我不在这里讨论它,但如果您想了解设置方法,请参考以下文章。

广告
将在 10 秒后关闭
bannerAds