前言
使用 Typescript 开发 React 项目,推荐使用 Visual Studio Code 编辑器。
① 创建项目工程
mkdir project
cd project
yarn init
② 安装依赖包
安装 React 框架
yarn add react react-dom
安装 React 类型库 (帮助 Typescript 识别 React 库中定义的类型)
yarn add --dev @types/react @types/react-dom
安装 Typescript 和 ts-loader
yarn add --dev typescript ts-loader
安装 Webpack
yarn add --dev webpack webpack-cli webpack-dev-server webpack-merge
安装 Webpack 插件
yarn add --dev source-map-loader html-webpack-plugin clean-webpack-plugin uglifyjs-webpack-plugin
③ 配置 webpack
定义配置中所需要用到的文件路径
./config/paths.js
const path = require('path')
const fs = require('fs')
const appDirectory = fs.realpathSync(process.cwd())
const resolveApp = relativePath => path.resolve(appDirectory, relativePath)
module.exports = {
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appIndex: resolveApp('src/index.tsx'),
appHtml: resolveApp('public/index.html'),
}
定义公用的 webpack 配置
./config/webpack/webpack.config.common.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const paths = require('../paths')
module.exports = {
resolve: {
extensions: ['.tsx', '.ts', '.js', '.json']
},
devtool: 'source-map',
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
},
{
test: /\.(ts|tsx)$/,
loader: "ts-loader",
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'React + Typescript Project',
template: paths.appHtml,
inject: false,
}),
],
}
定义 development 环境 webpack 配置
./config/webpack/webpack.config.dev.js
const webpack = require('webpack')
const merge = require('webpack-merge')
const paths = require('../paths')
const commonConfig = require('./webpack.config.common')
module.exports = merge.smart(commonConfig, {
mode: 'development',
entry: paths.appIndex,
output: {
filename: 'static/js/[name]-bundle-[hash:8].js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin()
],
devServer: {
// 开启前端路径回路映射,子路径映射到根路径,由前端路由框架来解析
historyApiFallback: true,
// 关闭 Host 检查,同网段其他设备,可通过内网 IP 访问本机服务(需要配合 host: '0.0.0.0')使用
disableHostCheck: true,
host: '0.0.0.0',
port: '8000',
inline: true,
hot: true,
// 请求代理服务
proxy: {
'/api': {
// 这里改为项目后端 API 接口 Host
target: 'http://backend.api.host',
// 支持跨域调用
changeOrigin: true,
}
}
}
})
定义 production 环境 webpack 配置
./config/webpack/webpack.config.prod.js
const merge = require('webpack-merge')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const paths = require('../paths')
const commonConfig = require('./webpack.config.common')
module.exports = merge.smart(commonConfig, {
mode: 'production',
entry: paths.appIndex,
output: {
path: paths.appBuild,
filename: 'static/js/[name]-[hash:8].js',
},
optimization: {
minimizer: [
// 压缩 js
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true
}),
],
splitChunks: {
// 切割代码块,提取为独立的 chunk 文件
chunks: 'all',
},
},
plugins: [
// 每次编译之前,清空上一次编译的文件
new CleanWebpackPlugin([paths.appBuild], {
root: process.cwd()
}),
],
})
④ 配置 tsconfig
./tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"jsx": "react",
"lib": ["es6", "dom"],
"module": "esnext",
"moduleResolution": "node",
"noImplicitAny": true,
"rootDir": "src",
"sourceMap": true,
"strict": true,
"target": "es5"
},
"exclude": [
"node_modules",
"build"
]
}
allowSyntheticDefaultImports: 允许合成默认导出
import * as React from 'react'
=>
import React from 'react'
⑤ 创建入口文件
./public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title><%= htmlWebpackPlugin.options.title %></title>
<% for (let css in htmlWebpackPlugin.files.css) { %>
<link href="/<%=htmlWebpackPlugin.files.css[css] %>" rel="stylesheet">
<% } %>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<% for (let chunk in htmlWebpackPlugin.files.chunks) { %>
<script type="text/javascript" src="/<%=htmlWebpackPlugin.files.chunks[chunk].entry %>"></script>
<% } %>
</body>
</html>
./src/index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(
<div>Hello React</div>,
document.getElementById('root'),
)
⑥ 配置 package 启动脚本
./package.json
{
...,
"scripts": {
"start": "webpack-dev-server --open --colors --config config/webpack/webpack.config.dev.js",
"build": "webpack --progress --colors --config config/webpack/webpack.config.prod.js"
},
...
}
⑦ 验收成果
基于 Typescript 的 React 基础框架就搭建好啦!
运行下面的命令,就可以在浏览器里看到 “Hello React” 欢迎页啦。
yarn start
运行下面的命令,就可以在 build 目录中看到编译好的「产品环境」文件啦。
yarn build
未完待续。。。
关于 react-router、redux、redux-saga、ant-design、jest 等其他配置,会在后续章节中更新。