react项目构建流程

159 阅读2分钟

1: 使用react脚手架搭建项目,并启用typescript。

npx create-react-app my-app --template typescript

-- 结果
搭建了react初始化项目,具体内容应版本差异而有所不同。 image.png

2: eslint的集成

先按照eslint的安装,然后执行eslint的初始化。

npm install eslint --save-g
npx eslint --init

3: prettier的集成

我们可以借助 Eslint 来提高我们编码的质量,但是却无法保证统一代码风格。一个统一的代码风格对于团队来说是很有价值的,所以为了达到目的,我们可以选择使用 Prettier 在保存和提交代码的时候,将代码修改成统一的风格。这样做同时也降低了 Code Review 的成本。它不会代替 Eslint,所以需要和 Eslint 搭配使用。

配置应用

1、 安装依赖

npm i -D prettier eslint-config-prettier eslint-plugin-prettier

2、 修改 Exlint 配置,打开 .eslintrc.js 文件,在扩展中增加  "plugin:prettier/recommended"  :

    "extends": [
        "plugin:prettier/recommended"
    ]

3、 增加 prettier 配置文件,在根目录创建 .prettierrc.js :

module.exports = {
  "printWidth": 120, //一行的字符数,如果超过会进行换行,默认为80
  "tabWidth": 2, //一个tab代表几个空格数,默认为2
  "singleQuote": true, // 单引号
}

4: 多环境配置的集成

npm i dotenv-cli react-app-rewired --save-dev

1、 创建多环境文件
image.png

2、 创建配置覆盖文件 image.png

3、 执行命令的修改

    "start": "dotenv -e .env.development react-app-rewired start",
    "build-test": "dotenv -e .env.test react-app-rewired build",
    "build-prod": "dotenv -e .env.production react-app-rewired build",

5: 将src作为全局路径设置

1、 在config-overrides.js里设置@映射到src目录

const path = require('path');

module.exports = function override(config) {
  config.resolve.alias['@'] = path.resolve(__dirname, 'src');

  return config;
};

2、 在根目录下创建paths.json文件,内容如下。

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

3、 在tsconfig.json里完成paths.json文件的加载

"extends": "./paths.json"

4、在eslint里parserOptions加下以下代码。

project: ['./tsconfig.json'],

--修正:

eslint修正:

    '@typescript-eslint/explicit-function-return-type': 'off',
    'react/react-in-jsx-scope': 'off',
    '@typescript-eslint/consistent-type-definitions': 'off',
    '@typescript-eslint/promise-function-async': 'off',
    '@typescript-eslint/no-floating-promises': 'off',
    '@typescript-eslint/strict-boolean-expressions': 'off',
    'max-len': ['error', 120],

tsconfig.json修正:

{
  "strictPropertyInitialization": false
}

如果你既不想在构造函数里赋值,也不想改变全局的配置,那么可以使用单次忽略配置

class A {
  // @ts-ignore
  name: string;
}

const a = new A();
console.log(a.name);

-- 至此:

react的基本骨架已完成。