step1: cd一个文件夹,执行下面的指令, 创建react项目

npm init vite@latest router-tutorial --template react

step2: 添加router

cd router-tutorial
npm install 
npm install react-router-dom@6
npm run dev

step3: main.jsx

import {render} from 'react-dom'
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import App from './App'
import Invoices from './invoices'
import Expenses from "./expenses";

const rootElement = document.getElementById("root");
render(
    <BrowserRouter>
        <Routes>
            <Route path="/" element={<App />}/>
            <Route path="/expenses" element={<Expenses />}/>
            <Route path="/invoices" element={<Invoices />}/>
        </Routes>
    </BrowserRouter>
    , rootElement
);

step4:app.jsx

import {Link} from 'react-router-dom'
import './App.css'

function App(){
  return (
      <div>
        <h1>test</h1>
          <nav style={{borderBottom:"solid 1px",paddingBottom:'1rem',}}>
              <Link to="/invoices">Invoices</Link>
              <Link to="/expenses">Expenses</Link>
          </nav>
      </div>
  );
}

export default App

step5:invoices.jsx

import './App.css'

function Invoices(){
    return (
        <main style={{padding:'1rem 0'}}>
            <h1 style={{color:"blue"}}>Invoices test</h1>
        </main>
    );
}

export default Invoices

step6: expenses.jsx

import './App.css'

function Expenses(){
    return (
        <main style={{padding:'1rem 0'}}>
            <h1 style={{color:"red"}}>Expenses test</h1>
        </main>
    );
}

export default Expenses

step7: package.json

{
  "name": "router-tutorial",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.2"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^1.0.7",
    "vite": "^2.8.0"
  }
}

npm run dev ,路由完成,可以通过link跳转 router路由

end