react工程笔记
-
新建项目
npm init vite
-
配置alias添加别名设置,因为是前后端分离 所以配置一下代理服务器
import { defineConfig } from 'vite' import path from 'path' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], resolve: { alias: { '@': path.resolve(__dirname, 'src'), // src 路径 } }, server: { proxy: { '/api': { target: 'http://localhost:8080', ws: false, changeOrigin: true, rewrite: path => path.replace(/^\/api/, '') } } } })
报错:配置这个的时候 dirname显示找不到
解决方案:npm install @types/node --save-dev
同时配置tsconfig.json
{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, "paths": { "@/*": ["./src/*"], }, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
-
使用less作为css预处理器
npm install -g less
-
安装react-router
npm i react-router-dom
配置路由表
新建src/routes/index.tsx
import {Index} from "@/pages/Index"; import {Navigate} from "react-router-dom" //创建路由 const routes = [ { path: '/index', element: <Index/>, }, { path: '/', element: <Navigate to="/index"/>, } ] export default routes;
-
引用路由,在App.js 组件内的使用
App.tsx
// 1.解构赋值引入需要使用的路由组件 import {useRoutes } from "react-router-dom" // 2.引入 路由表 import routes from "@/routes" function App() { // 根据路由表生成对应路由规则 const element = useRoutes(routes) return ( <> {/* 注册路由 */} {element} </> ) } export default App
-
入口文件修改为BrowserRouter模式
说明:如果使用了useRoutes()
,仍需要在最外层使用<HashRouter>
或<BrowserRouter>
包裹。
import React from 'react' import ReactDOM from 'react-dom/client' import { BrowserRouter } from 'react-router-dom'; import App from './App.tsx' import './index.css' ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( // <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> )
7.重置样式 然后再App.tsx引入
npm install --save normalize.css
8.安装tailwind.css,
npm install -D tailwindcss
9.新建tailwind.config.js
npx tailwindcss init -p
在新生成的文件中导入配置
/** @type {import('tailwindcss').Config} */ module.exports = { content: ["./src/**/*.{html,js,jsx,tsx}"], theme: { extend: {}, }, plugins: [], }
10.在index.css添加
@tailwind base; @tailwind components; @tailwind utilities;