如何从0到1,搭建一个现代最新的现代react+next.js项目

112 阅读6分钟

在这篇文章中,我将带你一步步从零开始,搭建一个现代前端工程:基于 React 19 + Next.js 15 + TailwindCSS 4,并集成 TypeScript、ESLint、Stylelint、Prettier、Ant Design 等现代开发工具,最终打造一个可维护、高性能、开发体验极佳的前端工程。

第 1 步:项目初始化

bash
npx create-next-app@latest next-demo --typescript

在交互过程中选择:

  • App Router(推荐)
  • Tailwind CSS:否(我们手动装最新版)
  • ESLint:否(我们自定义配置)
  • src/ 目录结构:是(推荐)
  • Experimental app/ directory:是

进入项目目录:

bash
cd next-demo

第 2 步:安装依赖(React 19、Next.js 15、Tailwind 4)

安装核心依赖:

bash
npm install react@^19 react-dom@^19 next@15

安装 TailwindCSS v4 及其相关依赖:

bash
npm install -D tailwindcss@^4 postcss autoprefixer

tailwindcss v4版本之后已经不需要配置文件我们直接引入就行了

在app下创建tailwind.css文件 app/tailwind.css 并引入 Tailwind:

@import 'tailwindcss';

新版引入方式 一次性将三个layer全部引入 简化配置

然后在app/globals.css中引入

@import './tailwind.css';

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

建议tailwind.css中自定义layer样式层,globals中可以自己定义全局的一些基本字体,样式的一些初始化等

app/layout.tsx 中引入:

import './globals.css';

创建postcss.config.mjs文件 这一步是为了构建不报错,如果没有的化构建的时候是不能够识别tailwindcss的,但是可以dev下可以正常开发:

export default {
  plugins: {
    '@tailwindcss/postcss': {}, //官方最新已经使用这种方式引入 老的引入方式会报错 
    autoprefixer: {},
  },
};

第 3 步:集成 Ant Design(支持 React 19)

bash
npm install antd @ant-design/v5-patch-for-react-19 @ant-design/nextjs-registry

app/layout.tsx 中注册样式支持(使用官方推荐方式):

import './globals.css';
import '@ant-design/v5-patch-for-react-19';

import { AntdRegistry } from '@ant-design/nextjs-registry';
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body>
        <AntdRegistry>{children}</AntdRegistry>
      </body>
    </html>
  );
}

第 4 步:添加 ESLint + TypeScript 支持

安装 ESLint 及相关插件:

npm install -D eslint @eslint/js 
  @typescript-eslint/eslint-plugin @typescript-eslint/parser 
  eslint-plugin-react eslint-plugin-react-hooks 
  eslint-plugin-import eslint-plugin-prettier 
  eslint-config-prettier eslint-plugin-simple-import-sort 
  globals

ESLint 配置 eslint.config.js 使用 Flat Config 模式 更现代:

import js from '@eslint/js';
import { defineConfig } from 'eslint/config';
import pluginImport from 'eslint-plugin-import';
import pluginPrettier from 'eslint-plugin-prettier';
import pluginReact from 'eslint-plugin-react';
import pluginSimpleImportSort from 'eslint-plugin-simple-import-sort';
import globals from 'globals';
import tseslint from 'typescript-eslint';

export default defineConfig([
  {
    ignores: ['node_modules/**', 'dist/**'],
  },
  {
    languageOptions: {
      globals: globals.browser,
    },
  },
  js.configs.recommended,
  tseslint.configs.recommended,
  pluginReact.configs.flat.recommended,
  {
    plugins: {
      react: pluginReact,
      prettier: pluginPrettier,
      import: pluginImport,
      'simple-import-sort': pluginSimpleImportSort,
    },
    rules: {
      'prettier/prettier': 'error',
      'react/react-in-jsx-scope': 'off',
      'react/prop-types': 'off',
      'import/no-extraneous-dependencies': ['error', { devDependencies: true }],
      '@typescript-eslint/no-unused-vars': ['warn'],
      'simple-import-sort/imports': 'error',
      'simple-import-sort/exports': 'error',
    },
    settings: {
      react: {
        version: 'detect',
      },
    },
  },
]);

注意现代趋势是都使用esm模式,这里需要在package.json中加入 "type": "module"

第 5 步:添加 Stylelint 支持(Tailwind + Less + SCSS)

实际上tailwind v4 官方不推荐使用别的css预处理器了 tailwind已经是一个css预处理器足够开发人员开发使用,当然如果开发习惯要使用也可以,不过需要自己在postcss中配置下。

npm install -D stylelint 
  stylelint-config-standard stylelint-config-tailwindcss 
  stylelint-config-standard-scss stylelint-config-recommended-less 
  stylelint-order

创建 stylelint.config.cjs

module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-tailwindcss',
    'stylelint-config-standard-scss',
    'stylelint-config-recommended-less',
  ],
  plugins: ['stylelint-order'],
  rules: {
    // 目前生态和eslint插件对最新版本的tailwind检测还存在问题,可能会报eslint错误 这里强制给去掉
    'at-rule-no-unknown': [true, {
      ignoreAtRules: ['tailwind', 'apply', 'mixin', 'include', 'function', 'if', 'else'],
    }],
    'scss/at-rule-no-unknown': [true, {
      ignoreAtRules: ['tailwind', 'apply', 'mixin', 'include', 'function', 'if', 'else'],
    }],
    'order/properties-order': [
      [
        'position', 'top', 'right', 'bottom', 'left',
        'display', 'width', 'height', 'margin', 'padding',
        'font', 'font-size', 'line-height', 'color',
        'background', 'border', 'box-shadow', 'z-index',
      ],
      { unspecified: 'bottomAlphabetical' },
    ],
  },
  cache: true,
  ignoreFiles: ['**/node_modules/**', '**/dist/**'],
};

第 6 步:Prettier 格式化工具配置

npm install -D prettier eslint-plugin-prettier eslint-config-prettier

创建 .prettierrc.json

{
  "semi": true,
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "trailingComma": "all",
  "arrowParens": "always",
  "endOfLine": "lf"
}

第 7 步:配置 TypeScript 编译规则(tsconfig.json

使用如下配置:

{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [{ "name": "next" }],
    "paths": { "@/*": ["./*"] },
    "forceConsistentCasingInFileNames": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

第 8 步:运行和开发

开发启动:

npm run dev

生产构建:

npm run build

可能存在的问题

1.报错lightningcss模块未找到问题

这是 Next.js 构建期间,Vite、Next、或者 Tailwind 内部工具链在用 lightningcss 做 CSS 处理的时候,动态引入 .node 二进制文件失败。

lightningcss 是一个用 Rust 写的 CSS 解析、压缩、处理工具。

1. Node 环境不兼容

  • lightningcss 的 .node 文件是和你的 Node.js 版本严格对应编译的。
  • 如果 Node 版本太高、太低或者切换过 Node 版本(nvm 切换过,或者 node_modules 用不同 Node 编译过),会报这个错。

检查 Node 版本:

node -v
  • lightningcss v1.x 一般推荐 Node 16.x ~ 20.x。
  • Node 21、22 不稳定。

更新 next.config.js

// next.config.js
module.exports = {
  experimental: {
    // 禁用 Turbopack 的 lightningcss 支持(临时解决方案)
    turbo: {
      resolveAlias: {
        'lightningcss': false
      }
    }
  }
}

//或者
module.exports = {
  experimental: {
    turbo: false  // 回退到 Webpack
  }
}

如果不是next.js的报错而是tailwindcss的引起的报错,很大可能是因为window系统的不支持,mac一般情况下不会报错

解决办法 安装 VC++ Redistributable 去搜下安装完成后就不会报错了

其他

vscode配置文件


{
  "editor.formatOnSave": true,
  "editor.formatOnType": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "always",
    "source.fixAll.stylelint": "explicit"
  },
  "eslint.useFlatConfig": true, //这里开启扁平化配置 否则vscode识别不了eslint的扁平配置文件
  "eslint.workingDirectories": [{ "mode": "auto" }],
  "files.eol": "\n",
  "javascript.updateImportsOnFileMove.enabled": "always",
  "typescript.updateImportsOnFileMove.enabled": "always",
  "typescript.preferences.importModuleSpecifier": "non-relative",
  "prettier.singleQuote": true,
  "prettier.semi": false,
  "prettier.trailingComma": "es5",
  "prettier.arrowParens": "avoid",
  "editor.fontLigatures": false,
  "[css]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[less]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "editor.fontWeight": "normal",
  "eslint.rules.customizations": [
    {
      "rule": "no-unused-vars",
      "severity": "error"
    },
    {
      "rule": "no-undef",
      "severity": "error"
    },
    { "rule": "react/react-in-jsx-scope", "severity": "off" }
  ],
  "stylelint.validate": ["css", "scss", "less", "vue", "postcss"],
  "css.validate": false,
  "autoimport.filesToScan": "**/*.{js,jsx,ts,tsx}",
  "editor.quickSuggestions": {
    "strings": "on"
  }
}

推荐vscode插件

  1. Auto Import && Auto import-es6,ts,jsx,tsx
  2. Auto Rename Tag
  3. chinese
  4. Code Spell Checker 单词检查,利器,有时候变量用了某个单词开发却拼错了自己是很难发现的,容易引起报错
  5. Color Info 样式开发,给css设置颜色的时候能够直接在编辑器中预览效果
  6. Docker 容器化部署 多人协作可能用到
  7. Dot Log

用法 xxx.log => console.log('xxx', xxx)
xxx.clg => console.log('xxx', xxx )
xxx.cwa => console.warn('xxx', xxx)
xxx.cer => console.error('xxx', xxx)
'xxxx'.log => console.log('xxxx')

  1. ES7+ React/Redux/React-Native snippets react编写常用语法补全
  2. EsLint
  3. Git Graph
  4. GitHub Pull Requests
  5. GitLens — Git supercharged
  6. Highlight Matching Tag 自动高亮匹配的标签
  7. HTML CSS Support 可能用到 在html中编写css的智能助手,可以不要
  8. Image preview
  9. Import Cost 计算引入的花费 性能优化相关
  10. Indenticator 缩进标识
  11. JavaScript (ES6) code snippets 写js会用到的一些自动提示
  12. JSON to TS 利器 分析Json文件直接生成类型定义
  13. Microsoft Edge Tools for VS Code
  14. Material Icon Theme
  15. Markdown Preview Enhanced 用vscode写文档会用到
  16. npm Intellisense
  17. Paste JSON as Code 直接转义json文件并预览
  18. Path Intellisense 只能路径分析
  19. PostCSS Language Support
  20. Prettier - Code formatter
  21. Regex Previewer 正则表达式匹配预览
  22. Sort Typescript Imports
  23. Stylelint
  24. Tailwind CSS IntelliSense
  25. TODO Highlight 未开发的功能用这个高亮显示 防止遗漏
  26. vscode-styled-components 如果使用styled-components 可以用这个插件
  27. sort-imports 引入排序(如果你自定义了规则)