vscode搭建react-typescript-webpack
mkdir react-ts-webpack-demo
cd react-ts-webpack-demo
touch webpack.config.js index.html
npm init -y
package.json
文件中。npm i webpack webpack-cli webpack-dev-server -D
npm i react react-dom -S
此时的packages.json文件自动配置安装的五个依赖包
npm i html-webpack-plugin --dev
npm i clean-webpack-plugin -S
npm i typescript ts-loader -D
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
mode: "development", //指定开发模式,默认为none
entry: "./src/index.tsx", //入口文件
output: {
path: path.resolve(__dirname, "dist"), //指定输出文件存放到dist文件夹中
filename: "bundle.js", //指定打包后生成的文件名称为bundle.js
},
module: {
rules: [
{
test: /\.tsx?$/, // 由awesome-typescript-loader 解析以.tsx结尾的文件
loader: "ts-loader",
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"], //定义解析文件的顺序,且引入这些文件可以不加后缀
},
plugins: [
//指定加载的index.html
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "index.html"),
}),
// 每次打包都自动删掉上一次打包留下的包(dist)
new CleanWebpackPlugin({}),
],
};
添加 tsconfig.json 文件,告诉 webpack 去哪儿寻找 typescript 文件以及编译选项配置,配置内容如下所示:
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node"
}
}
使用@types/前缀表示我们额外要获取 React 和 React-DOM 的声明文件
npm i @types/react @types/react-dom -D
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve": "webpack-dev-server",
"build": "webpack"
},
现在可以使用npm run serve
启动项目,npm run build
打包项目,打开之后是空白页面,因为还没有加入DOM元素对页面进行渲染。
目录结构如下所示:
packages.json文件如下所示:
{
"name": "react-ts-webpack-demo",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve": "webpack-dev-server",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"clean-webpack-plugin": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1"
},
"devDependencies": {
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.2"
}
}
ps:以上步骤参照文章:https://zhuanlan.zhihu.com/p/59023070,但是做的过程中发现页面渲染部分有问题,所以在文章的基础上重新做了改进。
在body标签里面创建一个id为root的div,方便入口文件获取
<!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>Document</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
使用createReact获取根元素root后将DOM渲染到该根元素下面:
import * as React from "react";
import { createRoot } from "react-dom/client";
const root = createRoot(document.getElementById("root"));
root.render(<h1>Hello world!</h1>);
react 18 用createRoot取代React17 的render函数去渲染DOM元素,开发的时候遇到了DOM没有渲染出来的问题,可以参考附录的开发过程记录文章区解决。
// 持续更新中。。。