Vite + React + Ant Design + Tailwind CSS + ESLint + Prettier + TypeScript 最佳实践

2022-08-11 01:58:46 +08:00
 nanxiaobei

很难过 Create React App 被时代淘汰,现在我们用 Vite 开发 React + Ant Design 吧。

很难过 CSS 被时代淘汰(明明没有好不好!),现在我们用 Tailwind CSS 吧。

很难过 yarn 被时代淘汰,现在我们用 pnpm 吧。

1. 用 Vite 生成一个 React + TypeScript 项目

pnpm create vite my-react-app --template react-ts

https://vitejs.dev/guide/#scaffolding-your-first-vite-project

2. 按照提示进入项目,安装依赖:

cd my-react-app
pnpm install

3. 安装 Ant Design 相关依赖

pnpm add antd @ant-design/icons
pnpm add -D less vite-plugin-imp # 用于按需引入组件

https://ant.design/docs/react/introduce#Using-npm-or-yarn

4. 修改 vite.config.ts 为如下内容:

import { defineConfig } from 'vite';
import vitePluginImp from 'vite-plugin-imp';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    vitePluginImp({
      optimize: true,
      libList: [
        {
          libName: 'antd',
          style: (name) => `antd/es/${name}/style`,
        },
      ],
    }),
  ],
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        // 如需定制 antd 主题,请取消以下内容注释 https://ant.design/docs/react/customize-theme
        // modifyVars: {
        //   hack: `true; @import "./src/theme.less";`,
        // },
      },
    },
  },
});

https://vitejs.dev/config/

5. 安装 Tailwind CSS 相关依赖

pnpm add -D tailwindcss postcss autoprefixer
npx tailwindcss init

Tailwind CSS ,用过都说好!几乎不用再添加 less/scss 文件,不用切换文件改完 CSS 再切回来,直接修改组件的 className 即可,"最短修改路径",便捷简洁现代化!(当然如果不想用可以不安装)

6. 按照 Tailwind CSS 官方指南配置

https://tailwindcss.com/docs/installation/using-postcss

注意:生成的 TypeScript 项目中,不支持 .js 配置文件,需使用 .cjs 文件。

touch postcss.config.cjs

postcss.config.cjs 内容:

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

tailwind.config.cjs 内容:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{html,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};

重命名 index.cssmain.css,修改其内容为:

@tailwind base;
@tailwind components;
@tailwind utilities;

6. 安装 ESLint 相关依赖

pnpm add -D eslint eslint-config-react-app

https://github.com/facebook/create-react-app/tree/main/packages/eslint-config-react-app

虽然 create-react-app 被淘汰了,但它的 ESLint 规则还是最权威的,开发 React 项目的最佳规范!

7. 安装 Prettier 相关依赖

pnpm add -D prettier eslint-config-prettier @trivago/prettier-plugin-sort-imports

https://github.com/prettier/eslint-config-prettier
https://github.com/trivago/prettier-plugin-sort-imports

@trivago/prettier-plugin-sort-imports,一个非常好用的对 import 进行自动排序的 Prettier 插件,用了就回不去了!(当然如果不想用可以不安装)

8. 添加 .eslintrc.cjs

touch .eslintrc.cjs
module.exports = {
  extends: ['react-app', 'prettier'],
};

9. 添加 .prettierrc.cjs

touch .prettierrc.cjs
module.exports = {
  singleQuote: true,

  // 以下为 @trivago/prettier-plugin-sort-imports 配置,若未使用可删去
  // importOrder 中的文件顺序规范,可依据项目实际情况自行更改
  plugins: [require.resolve('@trivago/prettier-plugin-sort-imports')],
  importOrder: [
    '^vite',
    '^react',
    '^antd',
    '<THIRD_PARTY_MODULES>',
    'components/',
    'pages/',
    'hooks/',
    'utils/',
    '^[./]',
  ],
  importOrderSortSpecifiers: true,
  importOrderGroupNamespaceSpecifiers: true,
  importOrderCaseInsensitive: true,
};

10. 大功告成,试试吧!

删除 App.css,修改 App.tsx 文件为:

import { useState } from 'react';
import { Button } from 'antd';
import { AlertOutlined } from '@ant-design/icons';
import reactLogo from './assets/react.svg';

function App() {
  const [count, setCount] = useState(0);

  return (
    <div className="grid place-content-center h-screen text-center text-lg">
      <div className="flex mx-auto items-center gap-8">
        <a href="https://vitejs.dev" target="_blank" rel="noreferrer">
          <img src="/vite.svg" className="w-28" alt="Vite logo" />
        </a>
        <a href="https://reactjs.org" target="_blank" rel="noreferrer">
          <img
            src={reactLogo}
            className="w-32 animate-spin [animation-duration:10s]"
            alt="React logo"
          />
        </a>
      </div>
      <h1 className="my-20 font-semibold text-6xl">Vite + React</h1>
      <div>
        <Button
          className="inline-flex items-center rounded-md"
          size="large"
          icon={<AlertOutlined />}
          onClick={() => setCount((count) => count + 1)}
        >
          count is {count}
        </Button>
        <p className="mt-4 mb-12">
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="opacity-40">
        Click on the Vite and React logos to learn more
      </p>
    </div>
  );
}

export default App;

启动项目:

pnpm run dev

耶寺!点开本地开发链接看看效果吧!

附赠

以上 shell 命令的合订版:

pnpm create vite my-react-app --template react-ts
cd my-react-app
pnpm install

pnpm add antd @ant-design/icons
pnpm add -D less vite-plugin-imp tailwindcss postcss autoprefixer eslint eslint-config-react-app prettier eslint-config-prettier @trivago/prettier-plugin-sort-imports

npx tailwindcss init
touch postcss.config.cjs
touch .eslintrc.cjs
touch .prettierrc.cjs
4567 次点击
所在节点    Vite
28 条回复
ChefIsAwesome
2022-08-11 13:41:55 +08:00
回想到上学的 java 课。毛程序都写不出来,尽在那配开发环境了。
Hanser002
2022-08-11 14:22:56 +08:00
刚试了下 `@trivago/prettier-plugin-sort-imports` 比 `eslint/import` 好用 已更换 感谢楼主
Hanser002
2022-08-11 14:25:03 +08:00
如果说 css 最佳实践 可以 @emotion + scss + tailwindcss , 之前看到的这个模板还不错 [vite-react-starter]( https://github.com/fabgrel10/vite-react-starter)
ohohohh
2022-08-30 11:22:25 +08:00
路由守卫要怎么搞呢?
iugo
2023-05-08 22:15:44 +08:00
和我们的技术栈还挺像的. 不过没有 Tailwind CSS. 我们项目是从 CRA 迁移来的.
no13bus
266 天前
@nanxiaobei 能否分享下项目结构,后续的一些东西,比如 component, layout, 模态对话框,项目文件夹是什么样的?我不太想用 nextjs ,太复杂了。我只是用 react 写前端,不想用什么 ssr 。
no13bus
266 天前
我自己很喜欢 vitejs, typescript 写的框架。干净,清爽。其实我觉得大部分用不到 nextjs 那些东西,不过 next 的周边生态很好,nextjs-auth 啥的,登陆都搞定了。
nanxiaobei
120 天前

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/872054

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX