nanxiaobei
V2EX  ›  Vite

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

  •  
  •   nanxiaobei ·
    nanxiaobei · Aug 11, 2022 · 7780 views
    This topic created in 1374 days ago, the information mentioned may be changed or developed.

    很难过 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
    
    Supplement 1  ·  Jan 15, 2024
    28 replies    2024-01-15 19:33:59 +08:00
    Aloento
        1
    Aloento  
       Aug 11, 2022   ❤️ 1
    buff 叠满了属于是
    iwh718
        2
    iwh718  
       Aug 11, 2022 via Android
    什么被淘汰的
    BugCry
        3
    BugCry  
       Aug 11, 2022 via Android
    要是能再套一层 Next 就 yyds 了
    gouflv
        4
    gouflv  
       Aug 11, 2022 via iPhone
    意义不明
    lingly02
        5
    lingly02  
       Aug 11, 2022   ❤️ 3
    OP 正好暴露了现在前端最大的问题:轮子太多,普通开发人员疲于追赶。光一个 CSS 就整出 scss,sass,less,Tailwind CSS 等,这还是主流的,非主流的就更多了, npm, yarn, pnpm 也是,就不能把 npm 好好优化一下吗?
    ccyu220
        6
    ccyu220  
       Aug 11, 2022
    《 yarn 被时代淘汰》
    mysalt
        7
    mysalt  
       Aug 11, 2022
    @lingly02 无比同意,现在的前端真的是轮子太多了,这要再加上 React 周边的各种轮子,简直要命
    yimity
        8
    yimity  
       Aug 11, 2022
    Tailwind 不要开 preflight ,甚至 import 可能还要 true 。不然会有很多和 ant 冲突的地方。
    nanxiaobei
        9
    nanxiaobei  
    OP
       Aug 11, 2022 via iPhone
    @BugCry 可以套,改天再水一篇,其实还有 stylelint 没加进去 😂
    IsaacYoung
        10
    IsaacYoung  
       Aug 11, 2022 via iPhone
    前端是这样的
    mywaiting
        11
    mywaiting  
       Aug 11, 2022
    这一堆整完,难怪大家都怀念 jQuery 粗快猛的年代~
    holystrike
        12
    holystrike  
       Aug 11, 2022
    用 vue 再水一篇吧😂
    coosir
        13
    coosir  
       Aug 11, 2022
    怀念 jQuery
    kytrun
        14
    kytrun  
       Aug 11, 2022
    当有人看不惯当前生态想自己造一个轮子一统天下的时候,这个世界上又多了一个轮子
    nomagick
        15
    nomagick  
       Aug 11, 2022
    政治正确一把梭,啥火用啥一把梭,
    这不是最佳实践,这是 Hell on earth.

    这项目有一点可维护性吗,明年这项目还能在吗
    nanxiaobei
        16
    nanxiaobei  
    OP
       Aug 11, 2022
    @nomagick 看了下你的回复,你是 V2EX 驻场喷子吗
    stoluoyu
        17
    stoluoyu  
       Aug 11, 2022
    @holystrike vue 其实相对还好,官方都给了推荐,react 真是挑花眼。
    churchill
        18
    churchill  
       Aug 11, 2022
    应该不能叫最佳实践,这是教你怎么利用社区工具创建一个 hello world 工程,还没开始实践呢

    我理解的"实践"是这种 https://github.com/alan2207/bulletproof-react ,不过这家比较怂:It is an opinionated guide that shows how to do some things in a certain way. 没敢说是 best practice ,略输一筹呀
    nanxiaobei
        19
    nanxiaobei  
    OP
       Aug 11, 2022 via iPhone
    @churchill 确实,这标题太高调了,下次我一定不改
    scyuns
        20
    scyuns  
       Aug 11, 2022   ❤️ 1
    感谢 提供实践整合
    ChefIsAwesome
        21
    ChefIsAwesome  
       Aug 11, 2022   ❤️ 1
    回想到上学的 java 课。毛程序都写不出来,尽在那配开发环境了。
    Hanser002
        22
    Hanser002  
       Aug 11, 2022   ❤️ 1
    刚试了下 `@trivago/prettier-plugin-sort-imports` 比 `eslint/import` 好用 已更换 感谢楼主
    Hanser002
        23
    Hanser002  
       Aug 11, 2022
    如果说 css 最佳实践 可以 @emotion + scss + tailwindcss , 之前看到的这个模板还不错 [vite-react-starter]( https://github.com/fabgrel10/vite-react-starter)
    ohohohh
        24
    ohohohh  
       Aug 30, 2022
    路由守卫要怎么搞呢?
    iugo
        25
    iugo  
       May 8, 2023
    和我们的技术栈还挺像的. 不过没有 Tailwind CSS. 我们项目是从 CRA 迁移来的.
    no13bus
        26
    no13bus  
       Aug 22, 2023
    @nanxiaobei 能否分享下项目结构,后续的一些东西,比如 component, layout, 模态对话框,项目文件夹是什么样的?我不太想用 nextjs ,太复杂了。我只是用 react 写前端,不想用什么 ssr 。
    no13bus
        27
    no13bus  
       Aug 22, 2023
    我自己很喜欢 vitejs, typescript 写的框架。干净,清爽。其实我觉得大部分用不到 nextjs 那些东西,不过 next 的周边生态很好,nextjs-auth 啥的,登陆都搞定了。
    nanxiaobei
        28
    nanxiaobei  
    OP
       Jan 15, 2024
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2992 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 94ms · UTC 07:32 · PVG 15:32 · LAX 00:32 · JFK 03:32
    ♥ Do have faith in what you're doing.