1.创建项目名称,在这里创建文件,my-react;
初始化项目
npm init -y
生成的package.json如下:
{
"name": "reactMy",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
2.安装webpack, webpack-cli:
npm i webpack webpack-cli -S
或者
yarn add webpack webpack-cli --dev
3.安装react, react-dom
npm i react react-dom -S
或者
yarn add react react-dom --dev
4.安装typescript
npm i typescript -S
或者
yarn add typescript --dev
5.使用npx typescript --init在根目录创建tsconfig.json文件,这是ts主要依赖的
npx typescript --init
6.在根目录创建文件夹src,在src下创建文件index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('App')
);
7.在根目录创建index.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>起步</title>
</head>
<body>
<div id="App"></div>
</body>
</html>
8.在根目录创建webpack.config.js,并配置入口和出口
const path = require('path');
module.exports = {
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
};
9.添加ts支持,识别ts,文件需要在webpack.config.js,里配置module
(1)安装yarn add ts-loader --dev
yarn add ts-loader --dev
module: {
rules: [{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
}]
},
10.添加生成html的插件
yarn add html-webpack-plugin --dev
在 webpack.config.js里添加
const HtmlWebpackPlugin = require("html-webpack-plugin");
// 在module.exports里配置
plugins: [
// 这里面是模板的位置,title是模板渲染的变量 htmlWebpackPlugin.options.title
new HtmlWebpackPlugin({
title: "test",
template: path.resolve(__dirname, "index.html"),
}),
]
11.添加types,才可以在tsx使用react-dom, react
yarn add @types/react-dom @types/react --dev
在tsconfig.json添加如下:
...
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true,
...
12.加入热更新webpack-dev-server
yarn add webpack-dev-server --dev
在package.json添加
"scripts": {
"test": "tsc",
"webpack": "webpack",
"start":"webpack-dev-server"
}
wepack.config.js修改
mode: "development",
devtool: 'source-map',
devServer: {
// host填写为0000是因为可能有remote开发的情况,0000不能访问就改成localhost
host: "0.0.0.0",
open: true,
},
13.加入clean-webpack-plugin,优化打包生成的dist
npm i clean-webpack-plugin -S
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// 在module.exports里配置
plugins: [
new CleanWebpackPlugin({
}),
]
14.最后几个配置文件的完整代码
(1)package.json
{
"name": "rwt",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^5.61.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
},
"devDependencies": {
"@types/react": "^17.0.33",
"@types/react-dom": "^17.0.10",
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"ts-loader": "^9.2.6",
"typescript": "^4.4.4"
}
}
(2)webpack.config.js文件
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: "development",
devtool: 'source-map',
devServer: {
// host填写为0000是因为可能有remote开发的情况,0000不能访问就改成localhost
host: "0.0.0.0",
open: true,
},
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
module: {
rules: [{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
}]
},
plugins: [
// 这里面的template是模板的位置,title是模板渲染的变量 htmlWebpackPlugin.options.title
new HtmlWebpackPlugin({
title: "test",
template: path.resolve(__dirname, "index.html"),
}),
new CleanWebpackPlugin({
}),
]
};
(3)tsconfig.json文件
{
"compilerOptions": {
"module": "commonjs", /* Specify what module code is generated. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
"jsx": "react",
"allowJs": true,
"outDir": "./dist/",
"target": "es5",
"sourceMap": true,
"moduleResolution": "node"
},
"include": [
"./src/**/*"
]
}
15.这时候一个比较简单的react+webpack+ts,就搭建完成了。
(1)使用npm run build,进行打包,可以看到如下图
(2)使用npm run dev启动项目
最后,还可以自己配react-router,或者react-router-dom,以及sass,css等等。
补充1:在项目中添加react-router-dom:
(1)安装react-router-dom
npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令
随后安装@types/react-router-dom
yarn add @types/react-router-dom --dev
(2)在src下创建pages文件夹,这里放页面,如下图:
home:创建home.tsx文件:
import React from 'react';
export default function home() {
return (
<div>我是home
<a href='#/Index'>去detail</a>
</div>
)
}
Index: 创建index.tsx文件:
import React from 'react';
export default function Index() {
return (
<div>我是Index
<a href='#/'>回到home</a>
</div>
)
}
(3)在src里创建router文件夹,在router下创建router.tsx,如下:
import React from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom';
import Home from '../pages/home/home';
import Index from '../pages/index/index';
const BasicRoute = () => (
<HashRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/Index" component={Index} />
</Switch>
</HashRouter>
);
export default BasicRoute;
(4)然后修改src下的index.tsx文件,如下:
import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router/router';
ReactDOM.render(
// <h1>Hello, world!</h1>,
<Router></Router>,
document.getElementById('App')
);
(5)在webpack.config.js里添加如下:
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
启动项目后:
补充2:在项目中添加css样式文件
(1)创建文件home.css,结构如下:
(2)home.css文件内容:
.home {
width: 100%;
height: 100px;
background: red;
}
.content {
width: 100%;
height: 20px;
background: pink;
}
(3)home.tsx文件引入home.css,
import React from 'react';
// 引入css文件
import './home.css';
export default function home() {
return (
// className类是class
<div className="home">我是home
<a href='#/Index'>去detail</a>
<div className="content">
我是内容。。。。。
</div>
</div>
)
}
(4)这时候会发现报错,其实是缺少css的相关loader配置,所以需要安装
yarn add css-loader style-loader
(5)在webpack.config.js里配置css,module,rules添加如下:
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
},
// css配置
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
},
最后重新打包,npm run build, 然后npm run dev,重新启动可以看到效果:
补充3:在项目中使用sass:
(1)安装node-sass,sass-loader
npm i node-sass sass-loader -S
(2)把home.css更改为home.scss
(3)修改home.tsx 引入样式的修改
import './home.scss';
(4)修改webpack.config.js,css的配置
{
test: /\.scss$/,
use:[
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
]
},
重新打包,重新启动,就可以使用sass了。