使用React18+Ts创建项目

1. 创建项目

首先,使用create-react-app工具创建一个新的React项目:

复制代码
npx create-react-app 项目名 --template typescript

2. 安装依赖项

使用脚手架创建项目后,自带react-dom等依赖项,但react中的所用的路由方法是react-router-dom中。

复制代码
npm install  react-router-dom 

3. 文件结构

默认情况下,create-react-app模板会自动生成一些文件和文件夹,这些文件和文件夹包括:

复制代码
- node_modules
- public
    |- index.html
    |- favicon.ico
- src
    |- App.css
    |- App.tsx
    |- index.tsx
    |- logo.svg
    |- react-app-env.d.ts
    |- setupTests.ts
- package.json
- README.md
- tsconfig.json
  • node_modules:存储所有的项目依赖项。
  • public:存储静态资源文件,例如 index.html 和 favicon.ico 文件。
  • src:存储应用程序的源代码。
  • App.css 和 App.tsx:是 React 组件的样式和逻辑。
  • index.tsx:是应用程序的入口。
  • tsconfig.json:存储 TypeScript 配置信息。

4. 配置样式

完成上述步骤后,我们还可以使用sass,less等预处理器来处理样式

复制代码
npm install sass stylelint stylelint-config-standard-scss --D

这样我们就可以直接在项目中使用sass样式。

5.配置路由

新建一个router文件夹,里面创建index.tsx文件

javascript 复制代码
import { lazy } from "react";
import { RouteObject } from "react-router-dom";
import Home from "../views/home";

const New = lazy(() => import("../views/editor/new") as any);
const Article = lazy(() => import(`../views/Article/[id]`) as any);
const routes: RouteObject[] = [
  {
    path: "/",
    element: <Home />,
  },
  {
    path: "/new",
    element: <New />,
  },
  {
    path: "/article/:id",
    element: <Article />,
  }
];

export default routes;

在App.tsx文件夹下使用路由

在根目录下的index.tsx包裹路由

运行成功后,你应该可以通过 http://localhost:3000 访问到你的应用程序。

最后放一个版本信息

相关推荐
踩着两条虫8 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB8 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
Spider Cat 蜘蛛猫8 小时前
Springboot SSO系统设计文档
java·spring boot·后端
即使再小的船也能远航8 小时前
【Python】安装
开发语言·python
Irissgwe8 小时前
类与对象(三)
开发语言·c++·类和对象·友元
雪度娃娃9 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
zyk_computer9 小时前
AI 时代,或许 Rust 比 Python 更合适
人工智能·后端·python·ai·rust·ai编程·vibe coding
萌新小码农‍10 小时前
python装饰器
开发语言·前端·python
KK溜了溜了10 小时前
Python从入门到精通
服务器·开发语言·python
雨辰AI10 小时前
SpringBoot3 项目国产化改造完整流程|从 MySQL 到人大金仓落地
java·数据库·后端·mysql·政务