新建文件夹 并进行项目初始化
- mkdir react-webpack-ts
- cd react-webpack-ts
- npm init
安装一些react依赖
npm i webpack webpack-cli -D
npm i react react-dom -S
npm i @types/react @types/react-dom -D
新建public/index.html文件
新建src/App.tsx文件
- import React from 'react'
-
- function App() {
- return <h2>react-webpack-ts</h2>
- }
-
- export default App
新建tsconfig.json文件
- {
- "compilerOptions": {
- "experimentalDecorators": true,
- "target": "ESNext",
- "useDefineForClassFields": true,
- "lib": [
- "DOM",
- "DOM.Iterable",
- "ESNext"
- ],
- "allowJs": false,
- "skipLibCheck": true,
- "esModuleInterop": false,
- "allowSyntheticDefaultImports": true,
- "strict": true,
- "forceConsistentCasingInFileNames": true,
- "module": "ESNext",
- "moduleResolution": "Node",
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noEmit": true,
- "jsx": "react",
- "baseUrl": ".",
- "paths": {
- "@/*": [
- "src/*"
- ]
- }
- },
- "include": [
- "./src/**/*.ts",
- "./src/**/*.tsx"
- ]
- }
新建index.tsx
- import React from 'react';
- import { createRoot } from 'react-dom/client';
- import App from './App';
-
- const root = document.getElementById('app');
- if(root) {
- createRoot(root).render(<App />)
- }
文件夹结构:
新建webpack.base.js 配置基本输入输出
- const path = require('path')
- const HtmlWebpackPlugin = require('html-webpack-plugin')
-
- module.exports = {
- // 入口文件
- entry: path.resolve(__dirname, '../src/index.tsx'),
- // 打包文件出口
- output: {
- filename: 'static/js/[name].[chunkhash:8].js', // 输出文件名称
- path: path.resolve(__dirname, '../dist'), // 打包的出口文件夹路径
- clean: true, // webpack4需要配置clean-webpack-plugin删除dist文件,webpack5内置了。
- publicPath: '/', // 打包后文件的公共前缀路径
- },
- }
安装一些依赖 解析我们的代码
npm i babel-loader @babel/core @babel/preset-react @babel/preset-typescript -D
npm i html-webpack-plugin -D
npm i webpack-dev-server webpack-merge -D
配置依赖
- module.exports = {
- ...,
- module: {
- rules: [
- {
- test: /.(ts|tsx)$/, // 匹配.ts, tsx文件
- use: {
- loader: 'babel-loader',
- options: {
- // 预设执行顺序由右往左,所以先处理ts,再处理jsx
- presets: [
- '@babel/preset-react',
- '@babel/preset-typescript'
- ]
- }
- }
- }
- ]
- },
- plugins: [
- new HtmlWebpackPlugin({
- template: path.resolve(__dirname, '../public/index.html'), // 模板取定义root节点的模板
- inject: true, // 自动注入静态资源
- })
- ],
-
- resolve: {
- extensions: ['.js', '.jsx', '.ts', '.tsx']
- }
- }
新建webpack.dev.js
- // webpack.dev.js
- const path = require('path')
- const { merge } = require('webpack-merge')
- const baseConfig = require('./webpack.base.js')
-
- // 合并公共配置,并添加开发环境配置
- module.exports = merge(baseConfig, {
- mode: 'development', // 开发模式,打包更加快速,省了代码优化步骤
- devtool: 'eval-cheap-module-source-map', // 源码调试模式,后面会讲
- devServer: {
- port: 3000, // 服务端口号
- compress: false, // gzip压缩,开发环境不开启,提升热更新速度
- hot: true, // 开启热更新,后面会讲react模块热替换具体配置
- historyApiFallback: true, // 解决history路由404问题
- static: {
- directory: path.join(__dirname, "../public"), //托管静态资源public文件夹
- }
- }
- })
修改package.json
-
- "dev": "webpack-dev-server -c build/webpack.dev.js"
然后项目就起来拉!qqqqq