無(wú)星的react之旅(一)—— 基礎(chǔ)項(xiàng)目設(shè)置問(wèn)題

記錄一些我碰到的入門(mén)問(wèn)題

1.如何創(chuàng)建ts項(xiàng)目

npx create-react-app app-name --template typescript

2.react+ts項(xiàng)目eslint如何引入

yarn add eslint --dev

npx eslint --init

選項(xiàng)如下:

? How would you like to use ESLint? … 
  To check syntax only
  To check syntax and find problems
? To check syntax, find problems, and enforce code style

? What type of modules does your project use? … 
? JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

? Which framework does your project use? … 
? React
  Vue.js
  None of these

? Does your project use TypeScript? ? No / Yes?

? Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Browser
  Node

? How would you like to define a style for your project? … 
? Use a popular style guide
  Answer questions about your style
  Inspect your JavaScript file(s)

? Which style guide do you want to follow? … 
? Airbnb: https://github.com/airbnb/javascript
  Standard: https://github.com/standard/standard
  Google: https://github.com/google/eslint-config-google

? What format do you want your config file to be in? … (任選)
  JavaScript
  YAML
? JSON

? Would you like to install them now with npm? ? No / Yes?

npm下載完成以后,刪掉package-lock.json,重新使用yarn去加載依賴

接著,以為已經(jīng)使用airbnb規(guī)則,萬(wàn)事大吉

但是你會(huì)發(fā)現(xiàn)特別多奇奇怪怪的錯(cuò)誤,比如

2.1 ‘React’ was used before it was defined

1.png

入口文件第一行提示react在未定義前被調(diào)用,這就很離譜。

實(shí)際上這是ts引起的,我們先看stackoverflow的問(wèn)題答案,再看tslint的文檔,應(yīng)該是ts聲明引起的。

因此我們需要在rules中添加

"rules": {
    "no-use-before-define": "off",
    "@typescript-eslint/no-use-before-define": ["error"]
}

2.2 Unable to resolve path to module ‘./App’

接著我們會(huì)遇到文件引入的問(wèn)題

2.png

我們需要添加一個(gè)庫(kù)eslint-import-resolver-typescript

yarn add eslint-import-resolver-typescript --dev

然后在.eslintrc.json添加settings,注意,不是rules

"settings": {
    "import/resolver": {
        "typescript": {}
    }
}

如果改完vscode還繼續(xù)報(bào)錯(cuò),重啟vscode

2.3 JSX not allowed in files with extension '.tsx'

3.png

rules添加

"rules": {
    "react/jsx-filename-extension": [
        2,
        {
            "extensions": [
                ".js",
                ".jsx",
                ".ts",
                ".tsx"
            ]
        }
    ],
}

2.4 Missing file extension "tsx" for "./App"

Missing file extension "ts" for "./reportWebVitals"

項(xiàng)目跑起來(lái),發(fā)現(xiàn)還有錯(cuò)誤
eslint添加rules

        "import/extensions": [
            "error",
            "ignorePackages",
            {
                "ts": "never",
                "tsx": "never"
            }
        ]

終于,項(xiàng)目跑起來(lái)了

總結(jié)一下:

# 1.添加eslint
yarn add eslint --dev
# 2.回答eslint的問(wèn)題
npx eslint --init
# 3.添加庫(kù)eslint-import-resolver-typescript
yarn add eslint-import-resolver-typescript --dev
# 4.為eslint添加規(guī)則,最后如下
{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "plugin:react/recommended",
        "airbnb"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "react",
        "@typescript-eslint"
    ],
    "settings": {
        "import/resolver": {
            "typescript": {}
        }
    },
    "rules": {
        "no-use-before-define": "off",
        "@typescript-eslint/no-use-before-define": [
            "error"
        ],
        "react/jsx-filename-extension": [
            2,
            {
                "extensions": [
                    ".js",
                    ".jsx",
                    ".ts",
                    ".tsx"
                ]
            }
        ],
        "import/extensions": [
            "error",
            "ignorePackages",
            {
                "ts": "never",
                "tsx": "never"
            }
        ]
    }
}

3.如何暴露webpack配置

方式1:

4.png

新建項(xiàng)目時(shí)說(shuō)的很清楚了,yarn eject,但是這樣做以后就無(wú)法返回之前收起來(lái)的狀態(tài)了。

作為從vue轉(zhuǎn)過(guò)來(lái)的,我們可以選擇一個(gè)類似vue.config.js的方式

方案2:

使用@craco/craco

yarn add @craco/craco

根項(xiàng)目下新建craco.config.js

module.exports = {};

package.json腳本修改

  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  },

4.設(shè)置別名,例如:src=@

4.1.修改craco.config.js

const path = require('path')

const pathResolve = pathUrl => path.join(__dirname, pathUrl)

module.exports = {
  webpack: {
        alias: {
            '@': pathResolve('src'),
            '@assets': pathResolve('src/assets'),
            '@components': pathResolve('src/components'),
        },
    }
};

4.2.修改tsconfig(加刪除線是因?yàn)闊o(wú)效)

修改tsconfig

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

看似好像在代碼中使用"@/xxx"不再報(bào)錯(cuò)了。

但是一旦使用yarn start運(yùn)行就會(huì)發(fā)現(xiàn),你加上的paths丟失了。

離譜不離譜

4.3.正確的做法

根目錄下添加paths.json文件

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

修改tsconfig文件

{
    "extends": "./paths.json",
    "compilerOptions":{
        ***
    }
}

4.4. eslint忽略@引入路徑

        "import/no-unresolved": [
            2,
            {
                "ignore": [
                    "^@/"
                ] // @ 是設(shè)置的路徑別名
            }
        ]

結(jié)束

到現(xiàn)在為止,項(xiàng)目上可能遇到基礎(chǔ)設(shè)置問(wèn)題,應(yīng)該都解決了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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