简单列表 (React+ React hook + TypeScript + webpack)
- React
17.0.1
- React Hook
- TypeScript
4.1.2
- webpack
5.10.0
$ yarn
//or
$ npm install
$ yarn add -D webpack webpack-cli
- 安装 react 的声明文件,由于 React 和 React-dom 并不是使用 TS 进行开发的,所以 TS 不知道 React、 React-dom 的类型,以及该模块导出了什么,此时需要引入 .d.ts 的声明文件。
$ yarn add react react-dom @types/react @types/react-dom
$ yarn add -D typescript
$ yarn add -D awesome-typescript-loader
$ yarn add -D style-loader less less-loader css-loader
7. 安装 html-webpack-plugin
yarn add -D html-webpack-plugin
- 根目录新增 webpack.config.js 文件
- 路径 ./webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const config = {
mode: "development",
entry: "./src/index.tsx",
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"],
},
module: {
rules: [
{
test: /\.tsx?$/,
use: ["awesome-typescript-loader"],
},
{
test: /\.less$/,
use: ["style-loader", "css-loader", "less-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
devServer: {
port: 3000,
open: true,
},
};
module.exports = config;
- src 目录新增 index.html 文件
- 路径 ./src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>列表页面</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div id="app"></div>
</body>
</html>
- src 目录新增 index.tsx 文件
- 路径./src/index.tsx
- 注意 ts 中 ReactDom 是小写
Dom
( 非 ReactDOM )
import * as React from "react";
import * as ReactDom from "react-dom";
import App from "./App";
ReactDom.render(<App />, document.getElementById("app"));
9.新增 tsconfig.json 处理 ts 文件
- 根目录新增 tsconfig.json 文件
- 路径./tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"allowJs": true,
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"removeComments": true
},
"include": ["./src/**/*"]
}
- 根目录新增.gitignore 文件
- 路径./.gitignore
# dependencies
/node_modules
/dist
...
"scripts": {
"dev": "webpack-dev-server",
"build": "webpack"
},
...