react之使用ts配置文件别名

一.使用ts构建的react项目,现在tsconfig.json文件中配置baseUrl和paths。由于直接在tsconfig.json里面配置paths字段后重启项目,会将配置好的paths自动移除,所以采用extends字段让tsconfig.json继承自定义的tsconfig.paths.json。步骤如下:

  1.现在项目根目录下创建tsconfig.paths.json文件,内容如下:

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

  2.在tsconfig.json中继承tsconfig.paths.json文件,使用了tsconfig.json提供的extends字段:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "experimentalDecorators": true
  },
  "include": [
    "src"
  ],
  "extends": "./tsconfig.paths.json"
}

  3.配置完tsconfig.json文件后,就需要安装customize-cra和react-app-rewired库:

    yard add customize-cra react-app-rewired --save-dev

  4.修改package.json:

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

  5.在项目根目录下新建config-overrides.js(只能是js文件,别建成ts文件了),内容如下:

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

module.exports =  override(
  addDecoratorsLegacy(),
  addWebpackAlias({
    "@": path.resolve(__dirname, './src')
  })
);

  6.配置完成,可以在项目中使用如:import App from "@/App"的导入方式了

customize-cra
posted @ 2021-08-09 22:47  vevian  阅读(964)  评论(0编辑  收藏  举报