4

Vite+React搭建开发构建环境实践 - 韩子卢

 2 years ago
source link: https://www.cnblogs.com/vvjiang/p/16693767.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用 Vite 已经有两年了,期间使用它开发过单页面应用,也开发过浏览器扩展插件,对比日常工作中用到的 webpack 构建速度大幅提升,开发体验也好很多。
虽然相比于 webpack 来说简单了很多,但是仍然有一些配置需要记录一下,以便之后可以快速搭建一个本地开发构建的环境。

使用 create-vite 脚手架生成基础模板

运行命令安装脚手架

yarn create vite

我在安装时提供的命令行选项那里,选择了 React + TypeScript。

使用下面的命令启动项目

yarn dev

此时的项目已经默认集成了 @vitejs/plugin-react 这个插件。

到这一步其实就已经基本结束了,自动集成 HMR,jsx,ts,css module,资源打包等一系列功能。

相比于 webpack,简直不要太友好。

eslint

先安装 eslint

yarn add eslint -D

然后初始化eslint配置:

yarn eslint --init

选择选项后,我自己安装的库大致是:

eslint-plugin-react@latest
eslint-config-standard-with-typescript@latest
@typescript-eslint/eslint-plugin@^5.0.0
eslint@^8.0.1
eslint-plugin-import@^2.25.2
eslint-plugin-n@^15.0.0
eslint-plugin-promise@^6.0.0
typescript@* // 这个可以移除

之后有两个方案:

  • 方案一,使用vite-plugin-eslint,这个会在报错时在页面上显示报错信息。
  • 方案二,使用 VSCode 的 ESlint 插件去使用 ESLint,这个是在代码上出现红线报错。(个人更喜欢这种)

方案二直接用插件即可,方案一需要安装一下库:

yarn add vite-plugin-eslint -D

安装完毕后,在vite.config.ts中配置:

//...
import eslint from "vite-plugin-eslint";

export default defineConfig({
    plugins: [react(), eslint()],
    //...
});

无论方案一还是方案二,此时仍会报错,因为 ESLint 无法解析 ts 代码,所以还需要安装 @typescript-eslint/parser

yarn add @typescript-eslint/parser -D

最后你还需要在.eslintrc.json 加上这行配置:

"parserOptions": {
    //...
    "project": "tsconfig.json"
},

基本完毕。

为什么说是基本?因为 eslint 配置还是更多跟代码习惯有关,比如单双引号的使用之类的,所以刚配置完一般都一堆报错,还需要自己去慢慢调整。

而且还涉及到与 prettier 的配置相冲突的问题,eslint 和 prettier 的配置分别是代码校验和代码格式化时的规则,所以也是要保证规则一致的。

手动调整规则太繁琐了,一般使用eslint-config-prettier禁用掉 ESLint 中和 Prettier 配置有冲突的规则,然后用eslint-plugin-prettier保证 eslint 用 prettier 的风格校验。

yarn add eslint-config-prettier eslint-plugin-prettier -D

然后在.eslintrc.json 中加上配置:

{
    "extends": [
        //...
        "plugin:prettier/recommended"
    ],
}

另外根据需要一般常用的配置列一下:

{
    "rules": {
        "react/react-in-jsx-scope":"off", // 使用 jsx 时不需要引用 React
        "@typescript-eslint/strict-boolean-expressions":"off" // 表达式中的布尔值必须严格是布尔类型
    }
}

这里也可能涉及到对tsconfig.json的修改:

{
  "compilerOptions": {
    "noImplicitAny":false, // 未声明类型的变量自动默认为any类型
  }
}

这里的配置较多,并且也因人而异,就不一一赘述了。

只要保持团队内部代码风格统一,就算是不符合标准规范的代码,其实也是好代码。

prettier

yarn add prettier -D

根目录下新建.prettierrc 配置文件,然后给个我自己用的配置方案:

{
    printWidth: 100,
    tabWidth: 4,
    useTabs: false,
    singleQuote: true,
    jsxSingleQuote: false,
    endOfLine: 'lf'
}

一般这个配合 VSCode 的 Prettier 插件和保存时格式化即可。

另外,对于 lf 和 crlf 的处理,保存时没法切换,需要在 VSCode 中设置。

react-router

yarn add react-router-dom

然后修改 main.tsx 中的代码吧:

//...
import {RouterProvider} from "react-router-dom";
import router from './router';

//...
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
    <React.StrictMode>
        <RouterProvider router={router} />
    </React.StrictMode>
);

这里我将路由相关代码放在了单独的路由文件 router.tsx 中:

import { createBrowserRouter } from 'react-router-dom';
import Framework from './Framework';
import Error from './Error';
import Home from '@/pages/home';
import About from '@/pages/about';

const router = createBrowserRouter([
    {
        path: '/',
        element: <Framework />,
        errorElement: <Error />,
        children: [
            {
                path: 'home',
                element: <Home />,
            },
            {
                path: 'about',
                element: <About />,
            },
        ],
    },
]);

export default router;

安装命令:

yarn add antd

然后在主 less 文件中加上代码:

@import 'antd/es/style/themes/default.less';
@import 'antd/dist/antd.less';

@primary-color: #4294ff; // 更换全局主色

然后还需要更改 vite.config.ts

//...
export default defineConfig({
     //...
    css: {
        preprocessorOptions: {
            less: {
                javascriptEnabled: true,
            },
        },
    },
});

通常我们会使用下面的方式来使用别名:

import reactLogo from "@/assets/react.svg";

默认情况下,会直接报错,所以我们需要在vite.config.ts进行如下配置:

//...
import path from "path";

export default defineConfig({
    //...
    resolve: {
        alias: {
            "@": path.resolve(__dirname, "src"),
        },
    },
});

这里因为没有 path 这个依赖库,所以还要运行命令安装:

yarn add path -D

此时别名功能已经可以正常使用,但是__dirname会报红,需要安装@types/node

yarn add @types/node -D

这时别名时没有智能提示的,所以还需要在tsconfig.json中,配置:

{
    "compilerOptions": {
        //...
        "baseUrl": "./",
        "paths": {
            "@/*": ["src/*"]
        }
    },
}

Less 与 CSS Module

Vite 已集成了 CSS Module 功能,但是想要使用 Less 还需要安装 less 这个库。

yarn add less

最后使用的方式如下:

import styles from "./App.module.less";

暂时就记录这么多吧,后续如果有一些别的功能配置,也会统一记录在这篇博客。

示例代码仓库:vite-react-practice


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK