首頁 > web前端 > js教程 > 主體

實例詳解VSCode配置react開發環境的步驟

小云云
發布: 2017-12-27 13:45:54
原創
5485 人瀏覽過

vscode 預設配置對於 react 的 JSX 語法不友好,體現在使用自動格式化或貼上後預設會縮排錯誤,儘管可以透過改變 language mode 來緩解錯誤,但更改 language mode 後的格式化依然不夠理想。本文主要介紹了VSCode配置react開發環境的步驟,小編覺得蠻不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧,希望能幫助大家。

透過搭配使用 ESLint 和 Prettier 外掛程式可以實現在 vscode 中完美支援 JSX 語法。

編輯器安裝外掛程式

##在vscode 中需要安裝下方外掛程式:

  1. ESLint

  2. ##Prettier
專案中的設定

設定ESLint

基礎配置

專案中安裝babel-eslint , eslint-plugin-jsx-a11y , eslint-plugin-react 依賴:


npm install babel-eslint eslint-plugin-jsx-a11y eslint-plugin-react --save-dev
登入後複製

推薦的ESLint設定如下(修改.eslintrc )


{
 // Use the AirBnB JS styleguide - https://github.com/airbnb/javascript
 "extends": "airbnb",

 // We use 'babel-eslint' mainly for React Native Classes
 "parser": "babel-eslint",
 "ecmaFeatures": {
  "classes": true,
 },

 // jsx相关插件
 "plugins": ["react", "jsx-a11y", "import"]

 // We can add/overwrite custom rules here
 "rules": {
  // React Native has JSX in JS files
  "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],

  // React Native includes images via require("../images/example.png")
  "global-require": 0
 }
}
登入後複製

需要注意幾點:

    如果使用yarn 安裝,需要手動建立.eslintrc 檔案
  1. 如果在使用過程中eslint 報錯,提示缺少依賴,安裝相關依賴就好
可能遇到的問題

如果在專案中檔名後綴是.js 而不是.jsx ,可能會遇到下面的錯誤:


複製程式碼

程式碼如下:

[eslint] JSX not allowed in files with extension '.js' (react/jsx-filename-extension)



#在.eslintrc 中加入新的rules 允許.js 和.jsx 後綴就好:

"rules": {
 "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }]
}
登入後複製

react-native 0.49 及以後版本已經不建議使用.jsx 為後綴了,參考這個討論No .jsx extension?

props validation 錯誤


##
[eslint] 'navigation' is missing in props validation (react/prop-types)
登入後複製

偵測props 的型別有助於寫出重複使用元件,最好不要把這個提醒關掉,如果一定要關,加入下面規則:

#
"rules": {
 "react/prop-types": 0
}
登入後複製


設定Prettier

我們想要的效果是: 設定Prettier 依照ESLint 的規則儲存檔案時自動格式化JSX 程式碼,步驟如下:

專案中安裝prettier-eslint


#
npm install prettier-eslint --save-dev
登入後複製


設定vscode workspace

在vscode workspace 使用者自訂部分新增以下程式碼:

#
// Format a file on save. 
// A formatter must be available, 
// the file must not be auto-saved, 
// and editor must not be shutting down.
"editor.formatOnSave": true,
  
// Enable/disable default JavaScript formatter (For Prettier)
"javascript.format.enable": false,
  
// Use 'prettier-eslint' instead of 'prettier'. 
// Other settings will only be fallbacks 
// in case they could not be inferred from eslint rules.
"prettier.eslintIntegration": true,
登入後複製

相關推薦:


實例詳解vue-cli vscode 設定eslint

##VSCode中預覽markdown和修改預覽樣式

總結整理VsCode外掛

#

以上是實例詳解VSCode配置react開發環境的步驟的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!