发布于 2026-01-06 8 阅读
0

使用 TypeScript、Tailwind CSS、ESLint 和 Jest 配置 Next.js

使用 TypeScript、Tailwind CSS、ESLint 和 Jest 配置 Next.js

Next.js可能是 2020 年和 2021 年搭建全新 React 项目的最佳方式。我甚至不知道是否值得进一步评价它,但 Next.js 团队确实做得非常出色!

它凭借构建坚不可摧的 Web 应用程序所需的所有功能脱颖而出:采用混合架构,支持 SSR、SSG 和 ISR,并且可以在Vercel平台上的无服务器运行时环境中进行托管。静态资源托管在 CDN 边缘网络中,实现快速交付,这才是它们应有的位置。🏃🏃🏃

那么,让我们用我们最喜欢的工具来配置 Next:Typescript 和 Tailwind CSS,我们将使用 ESLint 进行代码规范,并使用 Jest 来编写测试。

使用 TypeScript 配置 Next.js

打开终端并运行(将next-ts-tailwind替换为您所需的应用程序名称):

  • npx create-next-app next-ts-tailwind
  • cd next-ts-tailwind
  • 创建tsconfig.json文件:touch tsconfig.json
{
    "compilerOptions": {
      "allowJs": true,
      "alwaysStrict": true,
      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,
      "isolatedModules": true,
      "jsx": "preserve",
      "lib": ["dom", "ES2020"],
      "module": "esnext",
      "moduleResolution": "node",
      "noEmit": true,
      "noFallthroughCasesInSwitch": true,
      "noUnusedLocals": true,
      "noUnusedParameters": true,
      "resolveJsonModule": true,
      "skipLibCheck": true,
      "strict": true,
      "target": "esnext"
    },
    "exclude": ["node_modules"],
    "include": ["**/*.ts", "**/*.tsx"]
  }
Enter fullscreen mode Exit fullscreen mode
  • 添加 TS 依赖项
    yarn add --dev typescript @types/react @types/node

  • 请转到 /pages/index.js 并将其更改为 index.tsx

  • 运行yarn dev——一切顺利,运行良好http://localhost:3000/

设置 Tailwind CSS

Tailwind 团队已经编写了一个非常棒的教程,教你如何使用 Next.js 进行设置,但只需做一些小的改动就能让它与 TS 文件一起工作。

  • yarn add tailwindcss postcss autoprefixer
  • yarn add tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
  • npx tailwindcss init -p

  • 转到tailwind.config.js并进行更改purge: [],
    purge: ["./components/**/*.{js,ts,jsx,tsx}", "./pages/**/*.{js,ts,jsx,tsx}"],
    这样可以确保在构建生产环境时,最终的生产环境 CSS 文件中只会保留 Tailwind 框架中使用的类。如果你需要一个更专业的术语来让你的奶奶刮目相看,它叫做tree shaking。👵

  • 在 ./styles/global.css 文件的顶部添加 Tailwind 插件

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode
  • 找到你的pages/_app.js组件(应该将其重命名为 _app.tsx),并确保它看起来像这样:
import "../styles/globals.css";
import type { AppProps } from "next/app";

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode
  • 要测试 Tailwind 是否正常工作,请转到index.tsx并将其更改为:
import Head from "next/head";
import styles from "../styles/Home.module.css";

export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <div
        className="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4"
        role="alert"
      >
        <p className="font-bold">Be Warned</p>
        <p>You are using Tailwind CSS!</p>
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

运行该应用后,yarn dev您应该会看到:
顺风示例

设置 ESLint

  • yarn add --dev eslint
  • 跑题npx eslint --init并回答以下问题:

初始化 ESLint

转到package.json脚本部分,添加:
"lint": "eslint ."

现在,如果你尝试这样做yarn lint,你会看到一堆错误。请转到eslintrc.json并修改为:

{
    "env": {
        "browser": true,
        "es2021": true,
        "node": true,
        "jest": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "settings": {
        "react": {
            "version": "detect"   // Automatically detect the react version
        }
    },
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "react",
        "@typescript-eslint"
    ],
    "rules": {
        "react/react-in-jsx-scope": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off"
    }
}
Enter fullscreen mode Exit fullscreen mode

请注意,我还禁用了 `@ explicit-module-boundary-typesReturnType`,因为我喜欢 TypeScript 自动推断返回类型,但如果您希望始终为函数添加返回类型,则可以将其移除。此外,您可能还会看到其他一些 lint 警告,您可能不喜欢并会将其关闭,这完全没问题。

现在运行yarn lint应该不会出现任何警告和错误。

如果您使用 VSCode ,建议您安装ESLint VSCode 扩展。这样,您可以在编写代码时及时发现并修复错误。

添加 Jest

  • yarn add --dev babel-jest jest @types/jest @types/babel-generator
  • package.json脚本部分 - 添加"test": "jest --watch"
  • 在根目录下创建一个.babelrc文件,并在其中添加以下内容:
{
    "presets": ["next/babel"]
}
Enter fullscreen mode Exit fullscreen mode
  • 创建方式jest.config.js
module.exports = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
  testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
};
Enter fullscreen mode Exit fullscreen mode
  • 以及jest.setup.ts
import "@testing-library/jest-dom";
Enter fullscreen mode Exit fullscreen mode

接下来,我们来添加React 测试包:

  • yarn add --dev @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-event

在 components 文件夹中创建一个文件,SomeComp.test.tsx内容如下:

import { render } from "@testing-library/react";

function SomeComp() {
  return <div>Hello</div>;
}

describe("SomeComp", () => {
  it("renders Hello", () => {
    const { getByText } = render(<SomeComp />);
    expect(getByText("Hello")).toBeInTheDocument();
  });
});
Enter fullscreen mode Exit fullscreen mode

运行yarn test
通过 components/SomeComp.test.tsx
SomeComp
√ 渲染 Hello (24 毫秒)

结论

如果你已经看到这里,恭喜你!你已经成功配置了一个 Next.js 应用,其中包含 TypeScript、Tailwind CSS 和 ESLint,并且测试也已使用 Jest 和 RTL 设置完毕。🥳

如果你遇到困难或者想直接查看解决方案,可以在Github上查看

我在推特上发布了更多精彩内容🔥🔥。

文章来源:https://dev.to/alexandrudanpop/configuring-next-js-with-typescript-tailwind-css-eslint-jest-46ob