记录一下自己使用 webpack5从0到1搭建React+TypeScript 项目环境
创建项目目录
1. 生成package.json文件
$ npm init -y // -y 表示使用默认值
2. 创建项目目录
由于很多配置在「开发环境」和「生产环境」下是不一致的,所以在这里我分成了‘开发环境’和‘生产环境’ 让打包更加灵活
- webpack.config.dev.js // 开发环境下的配置
- webpack.config.prod.js // 生产环境下的配置
- webpack.config.common.js // 开发和生产都需要的配置
- webpack.config.js // 对不同环境下的配置进行整合
webpack.config.common.js
const { resolve } = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// webpack配置
// 入口文件
entry: './src/index.tsx',
output: {
// 输出的文件名
filename: 'script/[name].[contenthash].js',
// 输出路径
path: resolve(__dirname, '../dist'),
// 每次打包前 清空dist目录
clean: true
},
// loader 配置
module: {
rules: []
},
// 解析器
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"],
},
// 插件配置
plugins: [
new HtmlWebpackPlugin({
// 复制一个html文件 并将打包好的js文件引入
template: './index.html',
// 压缩 HTML
minify: {
collapseWhitespace: true, // 压缩空格
removeComments: true // 删除注释
}
})
]
}
webpack.config.dev.js
const Package = require('../package.json')
// ?? 非空运算符 当第一个参数为undefined或者null时,返回第二个参数,否则返回第一个参数。
const proxy = Package.proxy ?? {}
module.exports = {
module: {
rules: []
},
devtool: 'eval-cheap-module-source-map',
mode: 'development', // 开发模式
devServer: {
static: '../dist', // 将dist目录作为web服务器的根目录
compress: true, // 启用gzip压缩
port: 3000, // 设置开发服务器的端口号
hot: true, // 启用热更新
proxy, // 代理
// 解决SPA(单页应用)在路由跳转之后,进行页面刷新时,返回404的错误。
historyApiFallback: true
}
}
webpack.config.prod.js
module.exports = {
output: {
filename: 'script/[name].[contenthash].js'
},
module: {
rules: []
},
plugins: [],
mode: 'production' // 设置mode为production
}
webpack.config.js
// merge 用来合并webpack配置
const { merge } = require('webpack-merge')
const commontConfig = require('./webpack.config.common.js')
const developmentConfig = require('./webpack.config.dev.js')
const productionConfig = require('./webpack.config.prod.js')
module.exports = (env) => {
switch (true) {
case env.development:
return merge(commontConfig, developmentConfig)
case env.production:
return merge(commontConfig, productionConfig)
default:
// 或者抛出错误
return new Error('No matching configuration was found')
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
>
<title>Document</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
配置启动和打包命令
// package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "start": "webpack serve -c ./config/webpack.config.js --env development",
+ "build": "webpack ./config/webpack.config.js --env production"
},
配置React + TypeScript环境
$ npm install react react-dom
$ npm install @types/react @types/react-dom -D
or
$ yarn add react react-dom
$ yarn add @types/react @types/react-dom -D
index.tsx 文件
import React from 'react';
import ReactDOM from 'react-dom/client'
const App = () => {
return (
<div>
<h1>Hello, world!</h1>
</div>
)
}
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
添加 babel 配置
babel官网 传送🚪 https://www.babeljs.cn/
npm install babel-loader @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/plugin-transform-runtime @babel/runtime typescript -D
or
yarn add babel-loader @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/plugin-transform-runtime @babel/runtime typescript -D
创建babel配置文件
babel.config.json
{
"presets": [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript"
],
"plugins": [
[
"@babel/plugin-transform-typescript",
{
// Babel将使用regenerator-runtime来转换ts的声明文件,使其可以在旧版本的js环境中运行
"regenerator": true
}
]
]
}
需要在 webpack.config.common.js 添加规则
// webpack.config.common.js
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
]
}
}
},
]
},
配置 tsconfig.json
// 生成 ts配置文件
$ npx tsc --init
tsconfig.json 文件 删除多余配置项和注释
{
"compilerOptions": {
"target": "es2016",
"jsx": "preserve", /* Specify what JSX code is generated. */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src/", /* Specify the root folder within your source files. */
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
"outDir": "./dist/", /* Specify an output folder for all emitted files. */
"removeComments": true, /* Disable emitting comments. */
"esModuleInterop": true,
"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. */
}
}
启动 !!!
$ npm install webpack webpack-cli webpack-dev-server -D
or
$ yarn add webpack webpack-cli webpack-dev-server -D
在 index.tsx 添加
import React from 'react';
import ReactDOM from 'react-dom/client'
const App = () => {
return (
<div>
<h1>Hello, world!</h1>
</div>
)
}
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
最后 使用 · npm start · 或者 · yarn start · 直接启动
然后我们在浏览器中访问
http://localhost:3000
最后 狠狠拿下
当然 这里还有很多其他模块没有配置 例如 css、less 什么的 那个都简单 后面慢慢配.