react 也可以 @ 路径并给出路径提示

712 阅读2分钟

前言

CRA(create-react-app)的工程化配置是通过 webpack 来完成的,它将所有工程化配置都集成在了 react-scripts 包中,所以,项目中看不到任何配置信息或者是配置文件。

在开发中,我们需要根据情况来做一些配置,例如:支持用 @符号表示 src 地址。

如果要修改 CRA 的默认配置,有以下两种方案:

  • 通过第三方库来修改,比如,@craco/craco 。 【推荐】
  • 通过执行 yarn eject 命令,释放 react-scripts 中的所有配置到项目中,然后再做配置(注意:该操作不可逆!)

craco是什么

Create React App Configuration Override : an easy and comprehensible configuration layer for create-react-app

craco 是用来对 create-react-app 进行自定义配置的工具。

craco的使用步骤

react

1.安装包 npm i -D @craco/cracoyarn add -D @craco/craco

2.在项目根目录下,创建配置文件craco.config.js,配置路径别名

 // craco.config.js
    const path = require('path')
    module.exports = {
      webpack: {
        alias: {
          '@': path.join(__dirname, 'src') // 允许通过@符号来表示 src目录
        }
      }
    }

3.修改 package.json 中的脚本命令

 // 将 start/build/test 三个命令修改为 craco 方式
    "scripts": {
      "start": "craco start",
      "build": "craco build",
      "test": "craco test",
      "eject": "react-scripts eject"
    }

4.在项目根目录下,创建配置文件: jsconfig.json,添加如下配置

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

5.重启项目,让配置生效

vscode 会自动读取 jsconfig.json 中的配置,让 vscode 知道 @/ 就是 src/ 目录

react + typescript

1.安装包 npm i -D @craco/cracoyarn add -D @craco/craco

2.在项目根目录下,创建配置文件craco.config.js,配置路径别名

const path = require('path')

module.exports = {
  // webpack 配置
  webpack: {
    // 配置别名
    alias: {
      // 约定:使用 @ 表示 src 文件所在路径
      '@': path.resolve(__dirname, 'src'),
      // 约定:使用 @scss 表示 样式 文件所在路径
      '@scss': path.resolve(__dirname, 'src', 'assets', 'styles')
    },
  },
}

3.修改 package.json 中的脚本命令

// 将 start/build/test 三个命令修改为 craco 方式

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

4.在项目根目录下,创建配置文件: path.tsconfig.json,添加如下配置

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

5.tsconfig.json 中:

{
  // 导入配置文件
  "extends": "./path.tsconfig.json",
}