react+typescript+esLint+prettier初始化项目

使用create-react-app 脚手架

确保node/npm/yarn已经安装

yarn create react-app 项目名称 --template typescript

使用上方命令安装typescript项目

配置tsconfig.json文件

参考文章 tsconfig的配置

官网配置文件详解

tsconfig.json文件可以利用extends属性从另一个配置文件里继承配置, 根据需求自行配置

"extends": "./tsconfig.extend.json"

在根目录下新建tsconfig.extend.json文件

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

允许装饰器语法

"compilerOptions": {
    
    
	........
	"experimentalDecorators": true
}

使用craco扩展webpack配置

在react项目中修改webpack配置有2种方法,一种是执行 yarn eject命令暴露react的webpack配置文件进行修改,第二种方式是使用插件来扩展webpack,例如: antd推荐的craco或者customize-cra react-app-rewired等

  • 安裝插件@craco/craco

    yarn add @craco/craco -D
    
  • 修改package.json

    /* package.json */
    "scripts": {
          
          
    -   "start": "react-scripts start",
    +   "start": "craco start",
    -   "build": "react-scripts build",
    +   "build": "craco build",
    -   "test": "react-scripts test",
    +   "test": "craco test",
    
  • craco 配置文件详解

  • 安装其他craco插件

    yarn add craco-antd craco-less craco-alias @babel/plugin-proposal-decorators // 下载支持装饰器使用的模块
    
  • 在根目录下新建craco.config.js文件

    	const CracoAntDesignPlugin = require("craco-antd");
    	const CracoAlias = require("craco-alias");
    	const CracoLessPlugin = require("craco-less");
    	const path = require('path');
    
    	module.export = {
          
          
    	  plugins: [
    	    /* antd组件按需加载&样式覆盖等 */
    	    {
          
          
    	      plugin: CracoAntDesignPlugin,
    	      options: {
          
          
    	        customizeThemeLessPath: path.join(
    	          __dirname,
    	          'src/styles/antd.theme.less'
    	        )
    	      }
    	    },
    	    /* 支持less module */
    	    {
          
          
    	      plugin: CracoLessPlugin,
    	      options: {
          
          
    	        cssLoaderOptions: {
          
          
    	          modules: {
          
           localIdentName: '[local]_[hash:base64:5]' }
    	        },
    	        modifyLessRule: function (lessRule, _context) {
          
          
    	          lessRule.test = /\.(module)\.(less)$/
    	          lessRule.exclude = path.join(__dirname, 'node_modules')
    	          return lessRule
    	        }
    	      }
    	    },
    	    /* 别名设置 */
    	    {
          
          
    	      plugin: CracoAlias,
    	      options: {
          
          
    	        source: 'tsconfig',
    	        baseUrl: './src',
    	        tsConfigPath: './tsconfig.extend.json'
              }
    	    }
    	  ],
    	  devServer: (devServerConfig) => {
          
          
    	    return {
          
          
    	      ...devServerConfig,
    	      // 服务开启gzip
    	      compress: true,
    	      proxy: {
          
          
    	        '/api': {
          
          
    	          target: 'https://baidu.com/',
    	          changeOrigin: true,
    	          xfwd: false
              	 }
              }
            }
           }
         webpack: {
          
          
       		 // 配置别名,可以直接从根目录下面开始查找文件
    	    alias: {
          
          
    	      "@": resolve("src"),
    	      "components": resolve("src/components")
    	    }
     	 }
       }
    	
    
  • 在react-app-env.d.ts文件中新增(该文件运行项目自动生成)

  • 关于react-app-env.d的作用与用法

    /* 允许在ts中使用import styles from '*.less' */
    declare module '*.less' {
          
          
      const styles: any;
      export = styles;
    }
    

安装eslint规范代码

你可以选择airbnb或者standard代码风格规范代码

yarn add -D 
eslint-config-react-app 
@typescript-eslint/eslint-plugin@^4.0.0 
@typescript-eslint/parser@^4.0.0 
babel-eslint@^10.0.0 
eslint-plugin-flowtype@^5.2.0 
eslint-plugin-import@^2.22.0 
eslint-plugin-jsx-a11y@^6.3.1 
eslint-plugin-react@^7.20.3 
eslint-plugin-react-hooks@^4.0.8
  • 在根目录下新建.eslintrc.js
module.exports = {
    
    
  env: {
    
    
    browser: true,
    es6: true,
  },
  extends: ['react-app', 'standard', 'prettier'],
  parser: '@typescript-eslint/parser',
  plugins: ['react', 'react-hooks', '@typescript-eslint', 'import', 'prettier'],
  rules: {
    
    
    'prettier/prettier': 'error',
    'react/jsx-filename-extension': [
      2,
      {
    
     extensions: ['.js', '.jsx', 'ts', 'tsx'] },
    ],
    '@typescript-eslint/explicit-function-return-type': [
      0,
      {
    
     allowTypedFunctionExpressions: true },
    ],
    'react/state-in-constructor': 0,
    'import/extensions': [
      2,
      'ignorePackages',
      {
    
     ts: 'never', tsx: 'never', json: 'never', js: 'never' },
    ],
    'jsx-a11y/click-events-have-key-events': 0,
    'jsx-a11y/no-static-element-interactions': 0,
    'react/jsx-props-no-spreading': 0,
    'no-unused-expressions': 0,
    'jsx-a11y/anchor-is-valid': 0,
    'no-nested-ternary': 0,
    'react/static-property-placement': 0,
    'object-curly-newline': 0,
    'no-use-before-define': 'off',
    '@typescript-eslint/no-use-before-define': 0,
    '@typescript-eslint/no-var-requires': 0,
  },
  settings: {
    
    
    // ESLint 支持在配置文件添加共享设置。你可以添加 settings 对象到配置文件,它将提供给每一个将被执行的规则。
    // 如果你想添加的自定义规则而且使它们可以访问到相同的信息,这将会很有用,并且很容易配置。
    'import/resolver': {
    
    
      node: {
    
    
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
      typescript: {
    
    
        directory: './tsconfig.json',
      },
    },
  },
}

使用prettier规范代码风格

yarn add prettier eslint-config-prettier eslint-plugin-prettier -D
  • 在根目录下新建.prettierrc.js 配置如下:
module.exports =  {
    
    
  "semi": false,
  "singleQuote": true,
  "tabWidth": 2,
  "useTabs": false,
  "endOfLine": "auto"
}

使用stylelint检验css样式

yarn add stylelint stylelint-config-recommended stylelint-config-recess-order stylelint-config-standard -D
  • 在根目录下新建.stylelintrc.json 配置如下:
{
    
    
  "extends": [
    "stylelint-config-recommended",
    "stylelint-config-recess-order",
    "stylelint-config-standard"
  ],
  "rules": {
    
    
    "indentation": 2,
    "selector-pseudo-class-no-unknown": [ true, {
    
     "ignorePseudoClasses": ["global"] } ]
  }
}

增加pre-commit

yarn add pre-commit lint-staged -D

修改package.json的scripts

  "scripts": {
    
    
    "start": "set PORT=5000 && craco start",
    "build": "set GENERATE_SOURCEMAP=false && craco build",
    "test": "craco test",
    "lint": "tsc -p tsconfig.json --noEmit && eslint . --ext .jsx,.js,.ts,.tsx --fix && stylelint \"**/*.less\" --syntax=less --fix && prettier --write . --loglevel warn",
    "lint-staged": "lint-staged"
  },

在package.json增加

"lint-staged": {
    
    
  "**/*.{ts,tsx,less}": [
    "prettier --write"
  ],
  "**/*.{ts,tsx}": "yarn lint",
  "**/*.less": "stylelint --syntax less"
},
"husky": {
    
    
  "hooks": {
    
    
    "pre-commit": "yarn lint-staged"
  }
}

vscode setting.json配置

{
    
    
  // 关闭 TS 检查 JS 文件
  "javascript.validate.enable": false,

  // 保存文件时修正代码样式
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    
    
    // 开启 ESLint 修复
    "source.fixAll.eslint": true,
    // 开启 Stylelint 修复
    "source.fixAll.stylelint": true
  },
  // 设置默认的格式器为 Prettier
  "editor.defaultFormatter": "esbenp.prettier-vscode",

  // 开启 ESLint 验证
  "eslint.format.enable": true,

  // 设置 stylelint 的配置路径
  "stylelint.configFile": ".stylelintrc.json",
  // 设置 stylelint 需要检查的文件类型
  "stylelint.validate": [
    "css",
    "less",
    "sass",
    "scss"
  ],

  // 强制项目下有 Prettier 配置才开启样式修复
  "prettier.requireConfig": true,
  // 禁止 Prettier 使用 .editorconfig 配置,否则在没有 Prettier 的项目中也会格式化
  "prettier.useEditorConfig": false,

  // 在文件末尾插入新行
  "files.insertFinalNewline": true,
  // 删除每行末尾多余的空白
  "files.trimTrailingWhitespace": true,
  // 删除文件末尾多余的空行
  "files.trimFinalNewlines": true,
  // 强制每行结尾符为 "\n"
  "files.eol": "\n"
}

代码忽略

ESLint 代码忽略

// 忽略一行 // eslint-disable-line
alert("foo"); 

// 忽略下一行 // eslint-disable-next-line
alert("foo");

// 忽略代码块
/* eslint-disable */
alert("foo");
/* eslint-enable */

// 忽略指定的规则
alert("foo"); // eslint-disable-line no-alert, quotes, semi

Stylelint 代码忽略

/* 忽略一行 */
a {
    
    
  color: pink !important; /* stylelint-disable-line */
}

/* 忽略下一行 */
/* stylelint-disable-next-line */
a {
    
    
}

/* 忽略代码块 */
/* stylelint-disable */
a {
    
    
}
/* stylelint-enable */

/* 忽略指定的规则 */
/* stylelint-disable-next-line no-duplicate-selectors, block-no-empty */
a {
    
    
}

Prettier 代码忽略

// prettier-ignore
matrix(
  1, 0, 0,
  0, 1, 0,
  0, 0, 1
)
<div>
  {/* prettier-ignore */}
  <span ugly  format=''   />
</div>

问题

  • 待进一步深入了解eslint以及配置问题

参考

create-react-app + Typescript脚手架搭建
eslint整改代码遇到的问题和解决方案

Guess you like

Origin blog.csdn.net/shadowfall/article/details/121425369