返回

从0到1构建规范的React + Typescript 前端工程:一个详细指南

前端

从零搭建规范的 React + Typescript 前端工程

1. 项目初始化

安装 Node.js

Node.js 是 React 和 Typescript 运行必不可少的环境。确保已安装 Node.js。

初始化项目

创建一个新的项目,可以使用 npm 或 yarn,项目名随意,如 "my-react-project"。

安装 React

使用 npm 或 yarn 安装 React:

npm install react react-dom
或
yarn add react react-dom

安装 Typescript

同样使用 npm 或 yarn 安装 Typescript:

npm install typescript @types/react @types/react-dom
或
yarn add typescript @types/react @types/react-dom

配置 TypeScript

在项目根目录新建 tsconfig.json 文件,并添加如下内容:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "jsx": "react",
    "sourceMap": true,
    "noImplicitAny": true,
    "strictNullChecks": true
  }
}

2. 添加 Less

安装 Less

使用 npm 或 yarn 安装 Less:

npm install less less-loader
或
yarn add less less-loader

配置 Less

webpack.config.js 文件中添加如下内容:

module: {
  rules: [
    {
      test: /\.less$/,
      use: [
        'style-loader',
        'css-loader',
        'less-loader'
      ]
    }
  ]
}

3. 添加 ESLint

安装 ESLint

使用 npm 或 yarn 安装 ESLint:

npm install eslint eslint-plugin-react eslint-plugin-react-hooks eslint-config-airbnb
或
yarn add eslint eslint-plugin-react eslint-plugin-react-hooks eslint-config-airbnb

配置 ESLint

在项目根目录新建 .eslintrc.js 文件,并添加如下内容:

module.exports = {
  extends: ['airbnb', 'airbnb/hooks'],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
    'no-unused-vars': 'off',
    '@typescript-eslint/no-unused-vars': ['error'],
    '@typescript-eslint/no-explicit-any': 'off'
  }
};

4. 添加单元测试

安装 Jest

使用 npm 或 yarn 安装 Jest:

npm install jest @types/jest
或
yarn add jest @types/jest

配置 Jest

package.json 文件中添加如下内容:

"scripts": {
  "test": "jest"
}

5. 部署项目

构建项目

使用 npm 或 yarn 构建项目:

npm run build
或
yarn build

部署项目

将构建后的项目部署到服务器,可以使用 Nginx、Apache 或其他 Web 服务器。

总结

按照上述步骤,你已成功搭建了一个规范的 React + Typescript 前端工程。此工程包含常见的工具和配置,可助你快速开发和维护前端项目。

常见问题解答

1. 我应该使用 npm 还是 yarn?

两种包管理器都可以,根据个人喜好选择即可。

2. 我需要安装 webpack 吗?

不需要,我们已经通过 create-react-app 预先配置了 webpack。

3. 如何调试代码?

可以使用 Chrome DevTools 或其他调试工具调试代码。

4. 如何添加其他库或依赖项?

使用 npm 或 yarn 安装所需的依赖项,并在 webpack.config.js 中相应地配置。

5. 如何更新项目?

定期运行 npm updateyarn upgrade 以更新依赖项和工具。