当前位置: 首页>后端>正文

react 用 ts 开发react项目实现按照 eslint 规范格式化代码

  1. 使用 vscode 编辑器安装 Eslint 和 Prettier - code fromatter 插件
  2. 在项目中安装 prettier eslint 依赖和冲突解决策略依赖
npm install eslint prettier eslint-config-prettier eslint-plugin-prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react -D
  1. 在项目根目录新建 .eslintrc.js 进行自定义配置
module.exports = {
    env: {
        browser: true,
        es2021: true,
    },
    parser: '@typescript-eslint/parser',
    extends: ['plugin:react/recommended', 'plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended'],
    parserOptions: {
        sourceType: 'module',
        ecmaVersion: 'latest',
        ecmaFeatures: {
            jsx: true,
        },
    },
    rules: {
        'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx', '.ts'] }],
    },
    plugins: ['prettier', 'react'],
};
  1. 在项目根目录新建.prettierrc.js 进行自定义配置,如果没有则遵循 Prettier 默认规则进行格式化
module.exports = {
    semi: true,
    trailingComma: 'all',
    singleQuote: true,
    printWidth: 180,
    tabWidth: 4,
};
  1. 在项目根目录新建 .eslintignore,用于指定不用 eslint 校验的文件
build/*.js
src/assets
public
dist
.DS_Store
node_modules
/dist

/tests/e2e/videos/
/tests/e2e/screenshots/

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*

# Lock File
package-lock.json
yarn.lock

# autoGen
/autoGen
  1. 在项目根目录新建 .prettierignore,用于指定不用 prettier 格式化的文件
README.md
.DS_Store
node_modules
/dist

/tests/e2e/videos/
/tests/e2e/screenshots/

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*

# Lock File
package-lock.json
yarn.lock

# autoGen
/autoGen
/public/cdn
/public/cdnimages
  1. 对项目中所有文件同时进行格式化
    在 package.json 中的 scripts 属性下添加 format 项,通过 npm run format 命令实现项目全盘格式化
"scripts": {
    "format": "prettier --write \"**/*.+(js|jsx|json|css|md)\""
},

https://www.xamrdz.com/backend/3ys1934001.html

相关文章: