无星的react之旅(一)—— 基础项目设置问题

记录一些我碰到的入门问题

1.如何创建ts项目

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

2.react+ts项目eslint如何引入

yarn add eslint --dev

npx eslint --init

选项如下:

? 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  to select,  to toggle all,  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去加载依赖

接着,以为已经使用airbnb规则,万事大吉

但是你会发现特别多奇奇怪怪的错误,比如

2.1 ‘React’ was used before it was defined

1.png

入口文件第一行提示react在未定义前被调用,这就很离谱。

实际上这是ts引起的,我们先看stackoverflow的问题答案,再看tslint的文档,应该是ts声明引起的。

因此我们需要在rules中添加

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

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

接着我们会遇到文件引入的问题

2.png

我们需要添加一个库eslint-import-resolver-typescript

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

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

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

如果改完vscode还继续报错,重启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"

项目跑起来,发现还有错误
eslint添加rules

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

终于,项目跑起来了

总结一下:

# 1.添加eslint
yarn add eslint --dev
# 2.回答eslint的问题
npx eslint --init
# 3.添加库eslint-import-resolver-typescript
yarn add eslint-import-resolver-typescript --dev
# 4.为eslint添加规则,最后如下
{
    "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

新建项目时说的很清楚了,yarn eject,但是这样做以后就无法返回之前收起来的状态了。

作为从vue转过来的,我们可以选择一个类似vue.config.js的方式

方案2:

使用@craco/craco

yarn add @craco/craco

根项目下新建craco.config.js

module.exports = {};

package.json脚本修改

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

4.设置别名,例如: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(加删除线是因为无效)

修改tsconfig

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

看似好像在代码中使用"@/xxx"不再报错了。

但是一旦使用yarn start运行就会发现,你加上的paths丢失了。

离谱不离谱

4.3.正确的做法

根目录下添加paths.json文件

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

修改tsconfig文件

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

4.4. eslint忽略@引入路径

        "import/no-unresolved": [
            2,
            {
                "ignore": [
                    "^@/"
                ] // @ 是设置的路径别名
            }
        ]

结束

到现在为止,项目上可能遇到基础设置问题,应该都解决了

你可能感兴趣的:(无星的react之旅(一)—— 基础项目设置问题)