使用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 访问到你的应用程序。

最后放一个版本信息

相关推荐
bkspiderx1 小时前
Qt 插件机制:动态扩展应用功能的核心框架
开发语言·qt·元数据·qt 插件·qpluginloader
代码什么用1 小时前
Spring基础使用
java·后端·spring
程序员老陆1 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
沐晓时光1 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
明月_清风2 小时前
Deno 终局来了:从挑战 Node 到被 Cloudflare 收编
前端·后端·node.js
码云数智-园园2 小时前
unique_ptr 还是 shared_ptr?C++ 智能指针选型与内存泄漏实战分析
java·开发语言
蜗牛互联网2 小时前
Java 17 HttpClient调用文件转写API的超时与失败回退
java·人工智能·后端
禾小西3 小时前
07丨Redis 哨兵机制:主库故障后,如何恢复服务?
java·开发语言·redis
我不是阵雨3 小时前
JDK 21虚拟线程Pinning陷阱:一文拔钉解困
java·开发语言
徐小黑ACG3 小时前
Golang 基础05 结构体struct
开发语言·算法·golang