-
Notifications
You must be signed in to change notification settings - Fork 13
(一)初始化项目
阿峰 edited this page May 29, 2023
·
3 revisions
- 在开始webpack配置之前,先手动初始化一个基本的react+ts项目,新建项目文件夹react18-webpack5-ts, 在目录下执行
npm init -y
- 初始化好package.json后,在项目下新增以下所示目录结构和文件
├── build
| ├── webpack.base.js # 公共配置
| ├── webpack.dev.js # 开发环境配置
| └── webpack.prod.js # 打包环境配置
├── public
│ └── index.html # html模板
├── src
| ├── App.tsx
│ └── index.tsx # react应用入口页面
├── tsconfig.json # ts配置
└── package.json
- 安装webpack依赖
npm i webpack webpack-cli -D
- 安装react依赖
npm i react react-dom -S
- 安装react类型依赖
npm i @types/react @types/react-dom -D
- 添加public/index.html内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack5-react-ts</title>
</head>
<body>
<!-- 容器节点 -->
<div id="root"></div>
</body>
</html>
- 添加tsconfig.json内容
{
"compilerOptions": {
"target": "ESNext",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react", // react18这里也可以改成react-jsx
},
"include": ["./src"]
}
- 添加src/App.tsx内容
import React from 'react'
function App() {
return <h2>webpack5-react-ts</h2>
}
export default App
- 添加src/index.tsx内容
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
const root = document.getElementById('root');
if(root) {
createRoot(root).render(<App />)
}
现在项目业务代码已经添加好了,接下来可以配置webpack的代码了。