react学习第一篇:项目基础配置和遇到的问题

一、 新建项目

1.官网reactjs.org -- started -- 右侧 create a new React App文档

2. 找到新建项目命令

npx 必须的要 Node >= 10.16 and npm >= 5.6 才能使用----使用npx不需要在全局-g安装create-react-app,直接下面一句命令即可

npx create-react-app my-app  // 创建普通项目
or
npx create-react-app my-app --template typescript  // 创建ts项目
  1. 看看package.json
 "dependencies": {
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.6",
    "@testing-library/user-event": "^12.8.3",
    "@types/jest": "^26.0.23",
    "@types/node": "^12.20.11",
    "@types/react": "^17.0.4",
    "@types/react-dom": "^17.0.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",  // 主要的命令由它执行
  // ts 项目才有
    "typescript": "^4.2.4",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"    
// 先提交commit  才能执行npm run eject(eject本身即是弹出)
//会生成配置文件(config文件夹包含webpack.config.js,里面主要使用babel-loader 编译ts|mjs|jsx|js|tsx成js)
//可以更改配置文件依赖自定义编译需要的东西。基本上不使用命令生成项目不需要更改什么。需要更改使用下面第六点插件覆盖更改配置
  },

二、 升级普通项目为ts项目

1. 安装
npm i --save typescript @types/node @types/react @types/react-dom @types/jest
   
node,react, jest 并不是原生支持ts,所以需要typing文件@types/react
如果库原生支持ts就不需要这个,比如ng,vue3
@types/react : react ts 接口定义(也称typing)

2. js文件后缀改为tsx
3. 在app.js 引入 import React from 'react';
4. 运行项目, 会生成tsconfig.json文件

三、tsconfig.json配置解释

{
  "compilerOptions": {
 参数不需要加any类型
// "noImplicitAny": false,
 编译后目标js版本,便于浏览器识别。ES2015 ES2016 ES2018 ESNext
    "target": "es5", 
 编译期间要被包括进来的库,dom的库代表我可以使用操作dom的api,知道怎么检查。document.getElementById('root')
    "lib": ["dom", "dom.iterable", "esnext"],
允许混合编译js文件
    "allowJs": true,
    "skipLibCheck": true,
 允许使用commonjs的方式import 文件 import  React from 'react'
 // 未开启:import * as React from 'react'
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
 代码的模块系统  Nodejs的commonjs , es6的esnext,require的AMD
    "module": "esnext",
 编译器的工作方式。 将每个文件作为单独的模块使用
    "moduleResolution": "node",
 没有这个就无法引入json文件,引入会报错。而它又依赖moduleResolution
    "resolveJsonModule": true,
    "isolatedModules": true,
 发生错误时不会编译成js代码
    "noEmit": true,
 react-native 和 preserve表示不编译jsx
// react-native 输出扩展名为js,preserve输出扩展名.jsx
 react:编译为 react   例如:标签会编译成调用React 原生api方法生成,输出扩展名为js
// React.createElement("h1", null, "Hello world")
 react-jsx: 编译为 react17 新支持的功能 :react-jsx 不依赖 react 能稍微减少一些大小 
(react-jsx,react-jsxdev都是react17新增的)
// react-jsxdev 
    "jsx": "react"
  },
编译包含的文件路径
  "include": ["src"],
 列出始终会被编译的文件,不受exclude的影响
"files": ["./src/file.ts"] ,
 排除不编译的文件,不会影响include
"exclude": ["node_modules"] 

}

四、保存文件自动格式化

vscode设置---搜索词:保存 --- 勾选Format On Save (语言:vscode右下角 TypeScript React)

五、生成的项目默认tsconfig.json配置中 "jsx": "react-jsx",但是写代码发现报错

原因:vscode中的ts版本和新建项目的ts版本不一致,
随便找一个tsx文件,发现右下角ts react版本4.0.2
通过版本更新说明了解到 jsx 参数 react-jsx 是在4.1版本才添加的

企业微信截图_16196907111830.png
解决:脚手架create-react-app默认安装了最新的ts版本,切换为项目中的ts版本
 (1)打开到一个tsx文件
 (2)(cmd + shift + p)并键入“ select typescript version”,选择选项,
 (3) 选择“使用工作区版本4.2.4”。

or 简单点  直接右下角更新vscode版本
升级vscode 的ts版,vscode自带最新稳定版本ts

六、在项目配置alias 或者增加其他webpack配置

  1. 安装react-app-rewired 和 customize-cra
npm install react-app-rewired  customize-cra --D
  1. 在根目录新建config-overrides.js 文件
// config-overrides.js

const path = require("path");
const { override, fixBabelImports, addWebpackAlias } = require("customize-cra");

const alter_config = () => (config, env) => {
  const oneOf_loc = config.module.rules.findIndex((n) => n.oneOf);
  config.module.rules[oneOf_loc].oneOf = [
    //例如要增加处理less的配置
    // {
    //     test: /\.less$/,
    //     use: [
    //         require.resolve('style-loader'),
    //         {
    //             loader: require.resolve('css-loader'),
    //             options: {
    //                 importLoaders: 1,
    //             },
    //         },
    //         {
    //             loader: 'less-loader'
    //         }
    //     ],
    // },
    ...config.module.rules[oneOf_loc].oneOf,
  ];

  return config;
};

module.exports = override(
  alter_config(), //将自定义配置组合进来
  addWebpackAlias({
    //增加路径别名的处理
    "@": path.resolve("./src"),
  })
  //   fixBabelImports("import", {
  //     //antd UI组件按需加载的处理
  //     libraryName: "antd",
  //     libraryDirectory: "es",
  //     style: "css",
  //   })
);

  1. 修改package.json启动命令
可以发现,将react-scripts改为react-app-rewired
使用react-app-rewired来执行命令,在config-overrides.js插入配置
"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  1. 配置别名
根据ts文档,需要baseUrl 和paths配合
但是当我们重启项目,发现tsconfig.json文件会更新,paths 没了
{
  "compilerOptions": {
    "baseUrl": ".",  // This must be specified if "paths" is.
    "paths": {
      "@/*": ["src/*"]   // 此处映射是相对于"baseUrl"
    },
   "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
   ....
  }
}

解决如下
(1)在根目录新建paths.json
//paths.json
 {
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
(2)在tsconfig.json 中继承合并paths.json
// tsconfig.json
 {
  "extends": "./paths.json",
  "compilerOptions": {
    "target": "es5",
    ......
   }
}

正常使用绝对路径import Robot from "@/components/Robot";

你可能感兴趣的:(react学习第一篇:项目基础配置和遇到的问题)