悠悠楠杉
构建React+Vite项目:从零开始到配置完成
1. 初始化Vite+React项目
首先,你需要安装Node.js和npm(Node包管理器)。接着,在命令行中运行以下命令来创建一个新的Vite+React项目:
bash
npm create vite@latest my-react-app --template react
cd my-react-app
npm install
这将创建一个新的React应用目录,并安装必要的依赖。
2. 项目配置
2.1 安装依赖
在项目根目录下运行以下命令安装React Router等常用库:
bash
npm install react-router-dom axios @types/react-router-dom @types/axios --save-dev
2.2 配置环境变量
在项目根目录下创建.env
文件来设置环境变量:
dotenv
VITE_API_URL=https://api.example.com/
VITE_APP_VERSION=1.0.0
这些变量将在你的应用中通过process.env
访问。记得在.gitignore
中添加.env
文件以避免敏感信息上传到Git仓库。
3. 编写React组件和路由管理
在src/components
目录下创建你的React组件,例如Home.jsx
和About.jsx
。然后,在src/App.jsx
中引入并使用这些组件,并配置路由:
```jsx
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import './App.css'; // Import your global styles here if any.
function App() {
return (
);
}
export default App; // Export the App component for use in your index.js file.
``` 确保在src/index.js
中导入并渲染App
组件: ReactDOM.render(<App />, document.getElementById('root'));
。