# lss-react18-admin **Repository Path**: yuyingqianduan/lss-react18-admin ## Basic Information - **Project Name**: lss-react18-admin - **Description**: React18+pnpm+Ts+React-Router v6从0-1搭建后台系统 - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-11-16 - **Last Updated**: 2024-11-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # React18 + TypeScript + Vite5 - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh ## 前置知识 - [React](https://reactjs.org/) - [React Router](https://reactrouter.com/) - [Redux](https://redux.js.org/) - [Axios](https://axios-http.com/) - [Ant Design](https://ant-design.antgroup.com/index-cn) - [TypeScript](https://www.typescriptlang.org/) - [Vite](https://vitejs.dev/) - [ESLint](https://eslint.org/) - [Prettier](https://prettier.io/) - [Sass/SCSS](https://sass-lang.com/) - [PostCSS](https://postcss.org/) - [Husky](https://typicode.github.io/husky/#/) - [lint-staged](https://github.com/okonet/lint-staged) ## 创建项目 ```js pnpm create [项目名称] ``` ## 安装依赖 ```js pnpm install ``` ## 运行启动项目 ```js pnpm dev ``` ## 项目规范配置 规范基础配置文件:使得代码风格统一,提高代码可读性,减少代码冲突 ### 目录结构 ### 包管理器 - 使用`pnpm`作为包管理器 - 使用`pnpm`的原因: - 速度快,安装依赖更快 - 锁定版本,避免依赖版本不一致导致的问题 - 缓存机制,加速依赖安装 - 兼容性好,支持Windows、Mac、Linux ### .editorconfig 项目根目录下创建`.editorconfig`文件,用于统一编辑器配置 ``` root = true [*] charset = utf-8 indent_style = space indent_size = 2 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true ``` ### .prettierrc.cjs 项目根目录下创建`.prettierrc.cjs`文件,用于统一代码风格配置 ```js module.exports = { // 使用单引号代替双引号 singleQuote: true, // 尾随逗号,always:对象、数组、函数参数和返回值、类等最后添加逗号,never:不添加尾随逗号 trailingComma: 'all', // 每行最大列 printWidth: 120, // 缩进 tabWidth: 2, // 使用空格而不是 tab 进行缩进 useTabs: false, // 末尾添加分号,默认true semi: true, // 在对象字面量的大括号内加上空格 bracketSpacing: true, arrowParens: 'always', //对于 Markdown 文本,始终进行自动换行 proseWrap: 'always', // 在 HTML 中忽略空白符的敏感性,即不考虑空格、换行等对格式化的影响 htmlWhitespaceSensitivity: 'ignore', // 使用换行符(Line Feed,LF)作为行结束符 endOfLine: 'lf', }; ``` ### .vscode/settings.json 项目根目录下创建`.vscode/settings.json`文件,用于统一 VSCode 配置 (仅对当前项目有效) ```json { "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }, "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.formatOnSave": true } ``` ### eslint.config.js / .eslintrc.js 项目根目录下创建`eslint.config.js`文件,用于统一 ESLint 配置 项目自动生成的配置文件即可要不就按官网的命令生成 ```sh npm init @eslint/config@latest ``` ## Expanding the ESLint configuration If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: - Configure the top-level `parserOptions` property like this: ```js export default tseslint.config({ languageOptions: { // other options... parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, }, }); ``` - Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked` - Optionally add `...tseslint.configs.stylisticTypeChecked` - Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config: ```js // eslint.config.js import react from 'eslint-plugin-react'; export default tseslint.config({ // Set the react version settings: { react: { version: '18.3' } }, plugins: { // Add the react plugin react, }, rules: { // other rules... // Enable its recommended rules ...react.configs.recommended.rules, ...react.configs['jsx-runtime'].rules, }, }); ``` ## nprogress 进度条插件 ```shell ## 安装 nprogress 进度条插件 pnpm add nprogress ## 安装 @types/nprogress 类型声明 pnpm add @types/nprogress -D ``` ## antd UI 组件库 ```shell pnpm add antd pnpm add @ant-design/icons ``` ## react-router-dom安装路由 ```shell pnpm add react-router-dom ``` ## dayjs 时间处理插件 [dayjs](https://dayjs.fenxianglu.cn/),Day.js是一个极简的JavaScript库,可以为现代浏览器解析、验证、操作和显示日期和时 间,文件大小只有2KB左右。Day.js对国际化有很大的支持 ```shell pnpm add dayjs ``` ## normalize.css normalize.css 是一个用于重置浏览器默认样式的库,使得不同浏览器之间的渲染更加一致 ```shell pnpm add normalize.css ``` ## 样式方案 Less + CSS Modules 选择less 在使用 Ant Design (antd) 时,推荐使用 Less,原因如下:Ant Design 本身是用 Less 编写的,使用 Less 可以更容易地复 用和覆盖 antd 的默认样式变量可以直接使用 antd 提供的所有 Less 变量,便于主题定制以下是使用 Less 的配置和示例:首先安装必 要的依赖,react默认开启 css modules 所以不需要安装,样式文件需要以 `.module.less` 结尾 ```shell pnpm add less -D ``` ## 配置主题 [antd 定制主题能力](https://ant-design.antgroup.com/docs/react/customize-theme-cn) 注意:ConfigProvider 对 message.xxx、Modal.xxx、notification.xxx 等静态方法不会生效,原因是在这些方法中,antd 会通过 ReactDOM.render 动态创建新 的 React 实体。其 context 与当前代码所在 context 并不相同,因而无法获取 context 信息。 当你需要 context 信息(例如 ConfigProvider 配置的内容)时,可以通过 Modal.useModal 方法返回 modal 实体以及 contextHolder 节点,将其插入到你需要获取 context 位置即可。也可通过 App 包裹组件 简化 useModal 等方法需要手动植入 contextHolder 的问 题。 ## 配置多环境打包 根目录创建三个配置文件,更多环境一样如此操作 - .env.development (开发环境) - .env.staging (测试环境) - .env.production (生产环境) ```ts //.env.development VITE_APP_ENV = 'development'; VITE_APP_API_URL = /api / xxx务后地服本端 / xxx测试 / xxx生产都行; //.env.staging VITE_APP_ENV = 'staging'; VITE_APP_API_URL = xxx测试域名; //.env.production VITE_APP_ENV = 'production'; VITE_APP_API_URL = xxx生产域名; ``` ```json // package.json "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", // 新增打包命令 测试 生产 vue-tsc -b:表示 运行 TypeScript 类型检查 去掉也行(最好是别去掉因为本身用的ts项目) "build:staging": "vue-tsc -b && vite build --mode staging", "build:prod": "vue-tsc -b && vite build --mode production", }, ``` ## npm 设置代理 & 清空缓存 ```shell # 设置淘宝镜像 npm config set registry https://registry.npmmirror.com # 查看当前的源 npm config get registry # 更新 pnpm npm update -g pnpm # 强制删除 node_modules Remove-item -Force -Recurse node_modules # 清空 npm 缓存 npm cache clean --force ``` ## 自动重启 vite 服务 `vite-plugin-restart` 通过监听文件修改,自动重启 vite 服务 ```shell pnpm add vite-plugin-restart -D ``` ```ts // vite.config.ts import ViteRestart from 'vite-plugin-restart'; export default { plugins: [ ViteRestart({ // 一般就是这两个文件 restart: ['vite.config.ts', '.env.development'], }), ], }; ``` ## live-server 插件 ```shell pnpm add -g live-server ``` ## 使用缓存工具类 ```ts import { storage, sessionStorage, Storage } from '@/utils/storage'; // 1. 基本使用 interface UserInfo { id: number; name: string; email: string; } // 存储数据 storage.set('token', 'abc123'); storage.set('userInfo', { id: 1, name: 'John', email: 'john@example.com', } as UserInfo); // 获取数据 const token = storage.get('token'); const userInfo = storage.get('userInfo'); // 2. 设置过期时间 storage.set( 'tempData', { foo: 'bar' }, { expire: 60 * 60 * 1000, // 1小时后过期 }, ); // 3. 使用会话存储 sessionStorage.set('sessionId', '12345'); const sessionId = sessionStorage.get('sessionId'); // 4. 创建自定义实例 const customStorage = new Storage('localStorage', 'custom_'); // 5. 工具函数封装 export const userStorage = { // Token 相关 getToken: () => storage.get('token'), setToken: (token: string) => storage.set('token', token), removeToken: () => storage.remove('token'), // 用户信息相关 getUserInfo: () => storage.get('userInfo'), setUserInfo: (info: UserInfo) => storage.set('userInfo', info), removeUserInfo: () => storage.remove('userInfo'), // 清除所有用户数据 clear: () => { storage.remove('token'); storage.remove('userInfo'); }, }; // 6. 完整示例 function example() { // 存储不同类型的数据 storage.set('string', 'hello'); storage.set('number', 123); storage.set('boolean', true); storage.set('object', { a: 1, b: 2 }); storage.set('array', [1, 2, 3]); // 获取数据(带默认值) const str = storage.get('string', ''); const num = storage.get('number', 0); const bool = storage.get('boolean', false); const obj = storage.get>('object', {}); const arr = storage.get('array', []); // 检查是否存在 if (storage.has('string')) { console.log('string exists'); } // 获取所有键 const keys = storage.keys(); console.log('All keys:', keys); // 获取存储项数量 const count = storage.count(); console.log('Total items:', count); // 删除数据 storage.remove('string'); // 清空所有数据 storage.clear(); } ``` `live-server` 是一个轻量级的开发服务器,支持自动刷新和热重载。它非常适合用于本地开发和测试静态网站 `cd dist` 进入到打包 后端目录 执行 `live-server` 即可本地模拟服务 ### 常见问题 - Q: 找不到模块“path”或其相应的类型声明 - A: 安装 `@types/node` 依赖包 - Q: 找不到模块“@/views/login/Login”或其相应的类型声明 - A: 安装 `@types/node` 依赖包