1. 創(chuàng)建項目
首先,使用create-react-app工具創(chuàng)建一個新的React項目:
npx create-react-app 項目名 --template typescript
2. 安裝依賴項
使用腳手架創(chuàng)建項目后,自帶react-dom等依賴項,但react中的所用的路由方法是react-router-dom中。
npm install react-router-dom
3. 文件結(jié)構(gòu)
默認情況下,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:存儲靜態(tài)資源文件,例如 index.html 和 favicon.ico 文件。
- src:存儲應(yīng)用程序的源代碼。
- App.css 和 App.tsx:是 React 組件的樣式和邏輯。
- index.tsx:是應(yīng)用程序的入口。
- tsconfig.json:存儲 TypeScript 配置信息。
4. 配置樣式
完成上述步驟后,我們還可以使用sass,less等預(yù)處理器來處理樣式
npm install sass stylelint stylelint-config-standard-scss --D
這樣我們就可以直接在項目中使用sass樣式。
5.配置路由
新建一個router文件夾,里面創(chuàng)建index.tsx文件
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包裹路由
運行成功后,你應(yīng)該可以通過 http://localhost:3000 訪問到你的應(yīng)用程序。文章來源:http://www.zghlxwxcb.cn/news/detail-704107.html
最后放一個版本信息文章來源地址http://www.zghlxwxcb.cn/news/detail-704107.html
到了這里,關(guān)于使用React18+Ts創(chuàng)建項目的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!