下面是使用 TypeScript、React 和 Webpack 配置一个简单项目的步骤
1. 首先,创建一个新文件夹并打开终端,运行以下命令初始化 npm 项目
npm init -y
2. 安装 React 和 ReactDOM
npm install react react-dom
3. 安装 typescript 及其相关类型声明模块
npm install --save-dev typescript @types/react @types/react-dom
4. 安装 webpack 及其相关babel、插件
npm install --save-dev webpack webpack-cli html-webpack-plugin babel-loader @babel/preset-env @babel/preset-react @babel/preset-typescript
5. 在项目根目录中创建一个名为 src 的文件夹,并在其中添加一个 index.tsx 文件
import React from 'react';
import { createRoot } from 'react-dom/client';
const App: React.FC = () => {
return <div>hello world</div>;
};
createRoot(document.getElementById('root') as HTMLElement).render(<App />);
6. 在项目根目录中创建一个名为 public 的文件夹,并在其中添加一个 index.html 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Home</title>
</head>
<body>
<div id="root"> React not rendered!!</div>
</body>
</html>
7.在项目根目录中创建一个名为 webpack.config.js 的文件,并添加以下代码来配置 Webpack 打包设置:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
},
mode: 'development',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
},
module: {
rules: [
{
test: /\.(t|j)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-react',
'@babel/preset-env',
'@babel/preset-typescript',
],
},
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'public', 'index.html'),
filename: 'index.html',
}),
],
devServer: {
open: true,
hot: true,
compress: true,
port: 9000,
},
};
8.在 package.json 文件中修改 scripts 属性,添加以下内容来运行和打包应用程序
"scripts": {
"start": "webpack serve --config webpack.config.js",
"build": "webpack --mode production"
},