在打字稿中使用绝对路径进行导入 [英] using absolute paths in typescript for imports

查看:32
本文介绍了在打字稿中使用绝对路径进行导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目录结构是:

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

我想像这样导入A:

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

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

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

My tsconfig.json looks like this:

{
  "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"]
}

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

But the import does not work and I get the error:

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

can't find module 'src/components/A';

推荐答案

tsconfig.json 中定义 paths 像这样:

In tsconfig.json define paths like this:

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

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

(and you have to import it with name of file as well)

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

根据注释不需要带文件名导入,只要叫index即可(相对路径可以跳过/index)

based on the comments no need to import with file name as long as it is called index (With relative paths we can skip the /index)

这篇关于在打字稿中使用绝对路径进行导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆