react 用 ts 開發(fā)react項目實現(xiàn)按照 eslint 規(guī)范格式化代碼

  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 進(jìn)行自定義配置
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 進(jìn)行自定義配置,如果沒有則遵循 Prettier 默認(rèn)規(guī)則進(jìn)行格式化
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. 對項目中所有文件同時進(jìn)行格式化
    在 package.json 中的 scripts 屬性下添加 format 項,通過 npm run format 命令實現(xiàn)項目全盤格式化
"scripts": {
    "format": "prettier --write \"**/*.+(js|jsx|json|css|md)\""
},
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容