久しぶりにCRAをTSつきで使ったら、ちょいちょい詰まったのでメモ
プロジェクトの作成
# プロジェクト作成
npx create-react-app app --template typescript
# React17系から`React`のimport文は必要ないので削除
npx react-codemod update-react-imports
問題
VSCodeで Cannot use JSX unless the '--jsx' flag is provided.
と出る
解決策
エディタの右下の4.0.3
の部分をクリックし、TSのバージョン選択で、package.json
で指定しているTSのバージョンと合わせる
参考
ESLintの設定
# eslint初期化
$ npx eslint --init
# 以下、対話形式の質問と回答
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · react
✔ Does your project use TypeScript? · Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · airbnb
✔ What format do you want your config file to be in? · JSON
✔ Would you like to install them now with npm? · Yes
上記で生成された .eslintrc.json
に以下を追加
{
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"]
}
}
},
"rules": {
"@typescript-eslint/indent": [
"error",
2
],
"@typescript-eslint/prefer-interface": "off",
"react/jsx-filename-extension": [
"error",
{ "extensions": [".jsx", ".tsx"] }
],
"react/prop-types": "off",
"spaced-comment": [
"error",
"always",
{ "markers": ["/ <reference"] }
],
"react/react-in-jsx-scope": 0,
"import/extensions": 0
}
}
参考
VSCodeに必要な設定
保存時にeslintのフォーマットが行われる
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}