在打字稿中使用绝对路径进行导入

时间:2019-04-30 08:24:42

标签: typescript

我的目录结构是:

|
|__src
|    |_components
|                |
|                |_A
|                  |_index.tsx
|
|
tsconfig.json
package.json

我想这样导入A

从'src / components / A'导入{A};

我的tsconfig.json看起来像这样:

{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": true,
    "downlevelIteration": true,
    "esModuleInterop": true,
    "jsx": "react",
    "lib": ["es5", "es2015", "es2016", "dom"],
    "module": "esnext",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "outDir": "dist",
    "removeComments": false,
    "skipLibCheck": true,
    "strict": true,
    "strictFunctionTypes": false,
    "strictNullChecks": false,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es5",
    "typeRoots": ["./node_modules/@types"],
    "types": ["node", "jest"],
    "paths": {
      "*": ["./node_modules/@types/*", "./types/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.tsx"],
  "exclude": ["./node_modules", "./dist", "src/**/*.test.ts", "src/**/*.test.tsx"]
}

但是导入无法正常进行,并且出现错误:

  

找不到模块'src / components / A';

1 个答案:

答案 0 :(得分:1)

在tsconfig中定义这样的路径

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

,您还必须导入文件名

import { A } from 'src/components/A/index