Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

using absolute paths in typescript for imports

my directory structure is:

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

I want to import A like this:

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

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:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...