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

dag*_*da1 21 typescript

我的目录结构是:

|
|__src
|    |_components
|                |
|                |_A
|                  |_index.tsx
|
|
tsconfig.json
package.json
Run Code Online (Sandbox Code Playgroud)

我想这样导入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"]
}
Run Code Online (Sandbox Code Playgroud)

但是导入不起作用,我收到错误消息:

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

Jur*_*can 33

tsconfig.json定义paths是这样的:

{
  "compilerOptions": {
    "baseUrl": "./",
      "paths": {
        "src/*": [
          "./src/*"
        ],
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

(并且您还必须使用文件名导入它)

import { A } from 'src/components/A/index'
Run Code Online (Sandbox Code Playgroud)

基于注释不需要导入文件名,只要它被称为索引(使用相对路径,我们可以跳过 /index)

  • 节点,`"src/*": [` 中的尾随 `*` 很重要! (2认同)

Pin*_*nka 15

使用绝对路径的导入对我来说很有效,使用以下配置tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src"
  }
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json这是在 CRA 应用程序中适合我的完整内容:

{
  "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",
    "baseUrl": "src"
  },
  "include": [
    "src"
  ]
}
Run Code Online (Sandbox Code Playgroud)