Create-React-App 進階筆記

Create-React-App.png

CreateReactApp 是學(xué)習(xí) React 的必經(jīng)之路,其本身也值得深入學(xué)習(xí),本文記錄了如何給該腳手架添加一些額外功能

修改啟動端口

根目錄創(chuàng)建 .env.development 文件,寫入

PORT=4000

代碼包體積分析

安裝插件

npm install --save source-map-explorer

// 或
yarn add source-map-explorer

添加配置命令:在 package.json 中添加以下命令

  "scripts": {
    "analyze": "source-map-explorer 'build/static/js/*.js'",
  }

執(zhí)行打包命令后就可以使用命令分析打包后的代碼包了

npm run build
npm run analyze

集成 Eslint 和 Prettier

使用前提:VSCode 安裝并啟用了 EslintPrettier 插件,才會在編輯器中顯示提示信息

配置 Eslint

安裝并初始化配置

// 安裝 eslint 插件
npm install eslint --save-dev

// 初始化 eslint 配置
npm init @eslint/config

執(zhí)行初始化命令后,根據(jù)提示和需要選擇自己想要的配置,選在配置文件類型時

What format do you want your config file to be in?

建議選擇 JacaScript,方便寫注釋。上述所有命令執(zhí)行完成后會自動安裝以下幾個插件(版本可能會有變動), 并生成一個 .eslintrc.js 文件

// 安裝的插件
eslint-plugin-react@^7.28.0 
eslint-config-airbnb@latest 
eslint@^7.32.0 || ^8.2.0 
eslint-plugin-import@^2.25.3 
eslint-plugin-jsx-a11y@^6.5.1 
eslint-plugin-react-hooks@^4.3.0

附上生成的 .eslintrc.js 作參考:

module.exports = {
 env: {
   browser: true,
   es2021: true,
   node: true,
 },
 extends: [
   'eslint:recommended',
   'plugin:react/recommended',
 ],
 parserOptions: {
   ecmaFeatures: {
     jsx: true,
   },
   ecmaVersion: 'latest',
   sourceType: 'module',
 },
 plugins: [
   'react',
 ],
 rules: {
   // rules 根據(jù)自己的需要配置
 },
};

配置 Prettier

安裝 prettier 插件

// 安裝 prettier
npm install --save-dev prettier 

根目錄創(chuàng)建 prettier.config.js 配置文件,根據(jù)自己的需要配置格式化的規(guī)范,如:

// prettier.config.js

module.exports = {
  printWidth: 180, // 代碼換行的字符長度
  tabWidth: 2,
};

同時使用

由于 Eslint 和 Prettier 對會檢測代碼語法,同時使用時有可能造成規(guī)則沖突,因此需要額外安裝一些 插件,從而避免兩者的語法檢查產(chǎn)生沖突

npm install --save-dev eslint-plugin-prettier eslint-config-prettier

安裝完成后,在 eslint 的配置文件中加入 "plugin:prettier/recommended"

// .eslintrc.js 
{
    "extends": [
        "plugin:prettier/recommended"
    ]
}

到這里就已經(jīng)配置好了,可以放手開擼了,最好是重啟一下編輯器,部分沖突的配置需要重啟后才會生效。

常見錯誤解決

Delete ? eslint prettier/prettier

以上錯誤是由于行尾序列不一致導(dǎo)致的,只需要在 .prettier.config.js 中加入

{
    endOfLine: 'auto'
}

其他解決辦法可根據(jù)報錯信息自行搜索。

'React' must be in scope when using JSX react/react-in-jsx-scope

解決方案一:在所有使用到 react 語法的文件頂部引入 React

import React from 'react';

解決方案二:在 .eslintrc.js 配置文件中,給 extends 字段添加 plugin:react/jsx-runtime 表示兼容 jsx 新的語法

extends: [
    'eslint:recommended',
    'plugin:react/jsx-runtime', // 兼容 jsx 新的語法
]
最后編輯于
?著作權(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ù)。

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