ts-react-boilerplate 项目教程
1. 项目的目录结构及介绍
ts-react-boilerplate/
├── build/ # 构建输出目录
├── config/ # 配置文件目录
│ ├── jest/ # Jest 配置文件
│ ├── webpack/ # Webpack 配置文件
│ ├── paths.js # 路径配置
│ ├── webpack.config.js # 主 Webpack 配置文件
│ └── webpackDevServer.config.js # Webpack Dev Server 配置文件
├── public/ # 公共静态资源目录
│ ├── index.html # 主 HTML 文件
│ └── favicon.ico # 网站图标
├── scripts/ # 脚本目录
│ ├── build.js # 构建脚本
│ ├── start.js # 启动脚本
│ └── test.js # 测试脚本
├── src/ # 源代码目录
│ ├── components/ # React 组件目录
│ ├── containers/ # 容器组件目录
│ ├── routes/ # 路由配置目录
│ ├── store/ # Redux 存储目录
│ ├── styles/ # 样式文件目录
│ ├── index.tsx # 入口文件
│ └── App.tsx # 主应用组件
├── .babelrc # Babel 配置文件
├── .editorconfig # 编辑器配置文件
├── .eslintrc.js # ESLint 配置文件
├── .gitignore # Git 忽略文件配置
├── package.json # 项目依赖和脚本配置
├── README.md # 项目说明文档
└── tsconfig.json # TypeScript 配置文件
2. 项目的启动文件介绍
项目的启动文件是 src/index.tsx
。这个文件是整个应用的入口点,负责渲染根组件并挂载到 DOM 中。以下是 src/index.tsx
的主要内容:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
3. 项目的配置文件介绍
config/paths.js
这个文件定义了项目中各种路径的配置,包括源代码路径、构建输出路径等。
const path = require('path');
module.exports = {
src: path.resolve(__dirname, '../src'),
build: path.resolve(__dirname, '../build'),
public: path.resolve(__dirname, '../public'),
};
config/webpack.config.js
这是主 Webpack 配置文件,定义了如何打包和构建项目。
const webpack = require('webpack');
const paths = require('./paths');
module.exports = {
entry: paths.src + '/index.tsx',
output: {
path: paths.build,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: ['ts-loader'],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
};
tsconfig.json
这是 TypeScript 的配置文件,定义了 TypeScript 编译器的选项。
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "es2015"],
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./build",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src"]
}
通过以上配置文件,项目可以正确地进行开发、构建和部署。