10

我正在尝试在 tsconfig.json 中映射路径以摆脱相对路径的地狱。我的React App 基于 Create-React-App。我尝试了这个SO 线程并在我的 tsconfig.json 中添加了路径。我的 tsconfig.json 是

{
  "compilerOptions": {
    "baseUrl": "src",
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "strictNullChecks": false
  },
  "include": [
    "src"
  ]
}

当我在 VS Code 中编译我的项目时,它会从 tsconfig.json 中删除路径条目,并显示以下消息。为什么我的基于react-scripts的 React 项目不支持别名导入?

在此处输入图像描述

4

5 回答 5

4

不再支持路径别名

您现在可以这样做,直接导入相对于src目录的文件

转到您的jsconfig.json文件添加基本 URL"."

"compilerOptions": {
    "baseUrl":".",
    ...

然后你可以直接从src目录中导入东西

import Myfile from "src/myfile.js"
于 2021-08-13T22:38:09.203 回答
3

我通过将 to 更改为Angelo P 的回答工作config-overrides.js

const path = require('path');

module.exports = function override(config, env) {
  config.resolve = {
    ...config.resolve,
    alias: {
      ...config.resolve.alias,
      "@src": path.resolve(__dirname, 'src/'),
      "@api": path.resolve(__dirname, "src/API/"),
      "@assets": path.resolve(__dirname, "src/assets/"),
      "@components": path.resolve(__dirname, "src/components/"),
      "@containers": path.resolve(__dirname, "src/containers/"),
      "@css": path.resolve(__dirname, "src/css/"),
      "@customHooks": path.resolve(__dirname, "src/CustomHooks/"),
      "@helperFuncs": path.resolve(__dirname, "src/HelperFuncs/"),
      "@hoc": path.resolve(__dirname, "src/hoc/"),
      "@middlewares": path.resolve(__dirname, "src/middlewares/"),
      "@models": path.resolve(__dirname, "src/models/"),
      "@store": path.resolve(__dirname, "src/store/"),
      "@actions": path.resolve(__dirname, "src/store/actions"),
      "@reducers": path.resolve(__dirname, "src/store/reducers/"),
      "@sagas": path.resolve(__dirname, "src/store/sagas/"),
      "@typings": path.resolve(__dirname, "src/Typings/"),
      "@utils": path.resolve(__dirname, "src/utils/")
    },
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.json', '.d.ts']
  };
  return config;
};

像魅力一样工作,但唯一缺少的是 VSCode 自动补全。React 启动时会出现以下警告:

 The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

所以我假设它path从 tsconfig.json 中删除了该字段,并且 VSCode 无法获取别名,因此ESLintTS在 VSCode 中给出以下错误,但一切正常。

Unable to resolve path to module '@typings/...'.eslintimport/no-unresolved

Cannot find module '@typings/...' or its corresponding type declarations.ts(2307)

有人对此有解决方案吗?

更新

通过进行以下更改,设法使其全部正常工作:

tsconfig.paths.json

{
  "compilerOptions": {
    "paths": {
      "@src/*": ["./src/*"],
      "@api/*": ["./src/API/*"],
      "@assets/*": ["./src/assets/*"],
      "@components/*": ["./src/components/*"],
      "@containers/*": ["./src/containers/*"],
      "@css/*": ["./src/css/*"],
      "@customHooks/*": ["./src/CustomHooks/*"],
      "@helperFuncs/*": ["./src/HelperFuncs/*"],
      "@hoc/*": ["./src/hoc/*"],
      "@middlewares/*": ["./src/middlewares/*"],
      "@models/*": ["./src/models/*"],
      "@store/*": ["./src/store/*"],
      "@actions/*": ["./src/store/actions*"],
      "@reducers/*": ["./src/store/reducers/*"],
      "@sagas/*": ["./src/store/sagas/*"],
      "@typings/*": ["./src/Typings/*"],
      "@utils/*": ["./src/utils/*"]
    }
  }
}

注意*末尾的@.../*

tsconfig.json

{
  "extends": "./tsconfig.paths.json",
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext",
      "es2015.promise"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "plugins": [
      {
        "name": "typescript-plugin-css-modules"
      }
    ],
    "resolveJsonModule": true,
    "baseUrl": ".",
  },
  "include": [
    "src",
    "src/**/*.ts"
  ]
}

npm i -D eslint-plugin-import @typescript-eslint/parser eslint-import-resolver-typescript

.eslintrc.json

{
    ...,
    "settings": {
      "import/resolver": {
        "node": {
          "extensions": [".js", ".jsx", ".ts", ".tsx", ".d.ts"]
        },
        "typescript": {}
      }
    }
}
于 2021-09-27T13:11:50.627 回答
2

you've probably already figured this one out but here's a solution while we wait for a pull request that adds this to tsconfig Currently having the same issue with create-react-app react v 17.0.2,

I've had a similar issue with gatsby applications where you're not able to just set up alias imports without changing the web pack config

this thread has a good explanation on alias imports within cra without typescript, but it should lead to the same configuration at the end of the day.

you'd have to either eject(don't do this unless you have other issues you need to solve inside of your webpack config.) or use another package like CRACO or React-App-Rewired to configure your aliases through webpack.

This Stackoverflow answer is most likely what you're looking for.

install react-app-rewired then create config-overrides.js and place this code in there ->

//config-overrides.js
const { alias, configPaths } = require('react-app-rewire-alias');

module.exports = function override(config) {
  return alias(configPaths('./tsconfig.paths.json'))(config);
};

create your paths object inside of tsconfig.paths.json

//tsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@components": ["components"],
      "@styles": ["styles"],
      "@config": ["config"]
    }
  }
}

then extend these options inside of tsconfig (not inside compilerOptions)

//tsconfig.js

 "extends": "./tsconfig.paths.json"

finally, replace each react-scripts script in your package.json with react-app-rewired

//package.json
"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
},

You should be all set to go after this. Hoping this helps anyone else who runs into this problem with create-react-app.

于 2021-07-11T00:36:10.717 回答
1

您必须添加"baseUrl": ".",编译器选项,然后才能直接使用导入src/your/path

于 2021-01-28T22:43:03.403 回答
0

您不再需要craco解决这样的问题。我已经通过移动baseUrl到主tsconfig.json文件解决了这个问题,如下所示:

配置:

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

tsconfig.path.json:

{
    "compilerOptions": {
        "paths": {
            "api/*": ["api/*"],
            "assets/*": ["assets/*"],
            "config/*": ["config/*"],
            "components/*": ["components/*"],
            "hooks/*": ["hooks/*"],
            "pages/*": ["pages/*"],
            "store/*": ["store/*"],
            "constant/*": ["constant/*"],
            "types/*": ["types/*"],
            "utils/*": ["utils/*"]
        }
    }
}


于 2022-01-01T09:13:59.250 回答