• React + TypeScript 项目初始化配置


    React + TypeScript 项目初始化配置

    新建项目

    新建 React + TypeScript 项目:

    pnpm create @vitejs/app
    
    • 1

    进入项目目录,安装依赖并运行:

    pnpm install
    pnpm dev
    
    • 1
    • 2

    运行成功

    项目配置

    入口文件

    在 src 目录下创建 bootstrap.tsx 文件,并将入口文件的内容放到里面,然后将 bootstrap 引入到入口文件 index.ts 中:

    bootstrap.tsx

    import React from 'react'
    import ReactDOM from 'react-dom/client'
    import App from './App'
    
    ReactDOM.createRoot(document.getElementById('root')!).render(
      <React.StrictMode>
        <App/>
      </React.StrictMode>
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    index.ts

    import './bootstrap'
    
    • 1

    修改 index.html 中入口文件路径:

    安装 Mobx

    安装 mobx、mobx-react-lite 依赖:

    pnpm install mobx mobx-react-lite --save
    
    • 1

    新建 src/store/globalStore.ts 文件:

    globalStore.ts

    import {makeAutoObservable} from 'mobx'
    
    class GlogalStore {
      constructor() {
        makeAutoObservable(this)
      }
    }
    
    export default new GlogalStore()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    安装 Sass

    安装 sass:

    npm install sass --save-dev
    
    • 1

    新建 src/global.d.ts 声明文件:

    global.d.ts

    declare module '*.scss'
    
    • 1

    新建首页

    新建 src/pages/Index/index.module.scss 文件:

    .container {
        color: blue;
    }
    
    • 1
    • 2
    • 3

    新建 src/pages/Index/index.tsx 文件:

    Index/index.tsx

    import { observer } from 'mobx-react-lite'
    import styles from './index.module.scss'
    
    const Index = (props: any) => {
      return (
        <div className={ styles.container }>
            项目初始化
        </div>
      )
    }
    
    export default observer(Index)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    配置路由

    安装路由依赖:

    pnpm install react-router-dom -save
    
    • 1

    如果你只需要做网页应用的话,你需要的是 react-router-dom 而不是 react-router 这个包。它们的区别是,后者包含了 react-native 中需要的一些组件。

    将 App.tsx 更名为 RouterComp.tsx:

    RouterComp.tsx

    import { Routes, Route } from 'react-router-dom';
    import Index from './pages/Index/Index'
    
    // 用来作为 404 页面的组件
    const NotFound = () => {
      return <div>404</div>
    }
    
    const RouterComp = () => (
      <>
        <Routes>
            <Route path="/" element={<Index />} />
            <Route path="*" element={<NotFound />} />
        </Routes>
      </>
    )
    
    export default RouterComp;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    修改 bootstrap.tsx:

    bootstrap.tsx

    import ReactDOM from 'react-dom/client'
    import { BrowserRouter as Router } from 'react-router-dom'
    import RouterComp from './RouterComp'
    
    ReactDOM.createRoot(document.getElementById('root')!).render(
      <Router>
        <RouterComp />
      </Router>
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    配置 vite.config.ts

    vite.config.ts

    import { defineConfig } from 'vite'
    import {join} from 'path'
    import react from '@vitejs/plugin-react'
    
    function resolve(dir) {
      return join(__dirname, dir)
    }
    
    // https://vitejs.dev/config/
    export default defineConfig({
      root: process.cwd(), // 入口主文件项目的 index.html 当前路径开始
      // 配置服务器
      server: {
        https: false,
        cors: false, // 默认启用并允许任何源
        host: true, // 在 dev 场景下尽量显示声明 ip、port,防止`vite`启动时ip、port自动获取机制导致不准确的问题
        port: 3000, // 端口
      },
      // 打包配置
      build: {
        assetsInlineLimit: 40960, // 40kb
        outDir: 'dist', // 指定输出路径(相对于项目根目录)
        assetsDir: 'assets', // 指定生成静态资源的存放路径(相对于build.outDir)
        target: 'esnext',
        minify: false,
        cssCodeSplit: true,
        rollupOptions: {
          output: {
            minifyInternalExports: false,
          },
        },
      },
      // 插件配置
      plugins: [
        react()
      ],
      resolve: {
        alias: {
          'src': resolve('./src'),
        },
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
      },
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    此时,我们可以看到 root: process.cwd() 这个入口配置报错了,官网说这个是缺少了 node 的类型定义,运行它提示的命令的就行了:

    pnpm @types/node --save-dev
    
    • 1

    配置 tsconfig.json

    我们会发现,在 vite.config.ts 配置完主目录 alias 后依然报错,还需配置 tsconfig.json 即可解决:

    tsconfig.json

    {
      "compilerOptions": {
        "paths": {
          "src/*": ["./src/*"],
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    配置 Eslint

    安装 eslint 依赖:

    npm install @typescript-eslint/parser eslint eslint-plugin-standard @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-promise  --save-dev
    
    • 1

    在根目录下创建 .eslintrc.js 文件:

    .eslintrc.js

    const OFF = 0
    const WARN = 1
    const ERROR = 2
    module.exports = {
      env: {
        browser: true,
        commonjs: true,
        es6: true,
        node: true,
      },
      extends: 'eslint:recommended',
      parserOptions: {
        ecmaVersion: 6,
        sourceType: 'module',
        ecmaFeatures: {
          jsx: true,
          experimentalObjectRestSpread: true,
        },
      },
      parser: 'babel-eslint',
      plugins: ['react'],
      rules: {
        // 详细的规则
        quotes: [ERROR, 'single'], //单引号
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    在根目录下创建 .eslintignore 文件:

    .eslintignore

    # 自动生成的文件
    App.jsx
    main.jsx
    
    
    # 配置文件
    .eslintrc.js
    vite.config.js
    jsconfig.json
    
    # 构建文件
    dist/*
    build/
    
    # 其他
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    配置 Ant Design

    安装 antd:

    pnpm install antd --save
    
    • 1

    在入口文件中引入 antd 的全局样式:

    bootstrap.tsx

    import 'antd/dist/antd.css'
    
    • 1

    初始化全局样式

    新建 src/css/reset.scss:

    reset.scss

    /* http://meyerweb.com/eric/tools/css/reset/ 
       v2.0 | 20110126
       License: none (public domain)
    */
    
    html, body, div, span, applet, object, iframe,
    h1, h2, h3, h4, h5, h6, p, blockquote, pre,
    a, abbr, acronym, address, big, cite, code,
    del, dfn, em, img, ins, kbd, q, s, samp,
    small, strike, strong, sub, sup, tt, var,
    b, u, i, center,
    dl, dt, dd, ol, ul, li,
    fieldset, form, label, legend,
    table, caption, tbody, tfoot, thead, tr, th, td,
    article, aside, canvas, details, embed, 
    figure, figcaption, footer, header, hgroup, 
    menu, nav, output, ruby, section, summary,
    time, mark, audio, video {
    	margin: 0;
    	padding: 0;
    	border: 0;
    	font-size: 100%;
    	font: inherit;
    	vertical-align: baseline;
    }
    /* HTML5 display-role reset for older browsers */
    article, aside, details, figcaption, figure, 
    footer, header, hgroup, menu, nav, section {
    	display: block;
    }
    body {
    	line-height: 1;
    }
    ol, ul {
    	list-style: none;
    }
    blockquote, q {
    	quotes: none;
    }
    blockquote:before, blockquote:after,
    q:before, q:after {
    	content: '';
    	content: none;
    }
    table {
    	border-collapse: collapse;
    	border-spacing: 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    新建 src/css/global.scss,在该全局样式文件中引入:

    @import './reset.scss';
    
    • 1

    最后,在 vite.config.ts 文件中配置全局样式路径:

    vite.config.ts

      css: {
        //css预处理
        preprocessorOptions: {
          scss: {
            /**
    		 * 引入var.scss全局预定义变量,
    		 * 如果引入多个文件,
    		 * 可以使用
    		 * '@import "src/assets/scss/globalVariable1.scss";@import "src/assets/scss/globalVariable2.scss";'
    		 * 这种格式
    		 **/
            additionalData: '@import "src/css/global.scss";',
          },
        },
      },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    项目初始化完成

    运行项目如下图所示:

    则项目初始化成功。

  • 相关阅读:
    【附源码】计算机毕业设计SSM税务综合信息平台
    JAVA【数据库事务】【MySQL】
    HarmonyOS(鸿蒙系统)物联网开发教程——环境搭建
    typescript6-高级类型
    「SpringBoot」09 原理解析
    面试算法十问2(中英文)
    盛元广通开放实训室管理系统2.0
    基于 Linux 的 Docker Swarm 集群部署及应用
    设计模式之【模板方法模式】
    JS中localStorage和sessionStorage
  • 原文地址:https://blog.csdn.net/Jessieeeeeee/article/details/125498321