简体   繁体   中英

Cannot find module - typescript path alias error

On compile i get error that i can't fix:/

index.ts:2:19 - error TS2307: Cannot find module '@shared'

Any ideas why is it?

Project structure:

在此处输入图像描述

tsconfig.json:

{
  "compilerOptions": {
    "outDir": "../../build/backend",
  },
  "extends": "../../configs/tsconfig.base.json",
  "references": [
    {
      "path": "../shared"
    }
  ],
  "paths": {
    "@shared": [
      "../shared/index"
    ]
  }
}

backend/index.ts:

import 'module-alias/register'
import { x } from '@shared'

console.log(x)

shared/index.ts:

export const x = 'this is shared index'

You can use this command to trace problems:

tsc --traceResolution

As i found out '@shared' is used as folder name, so it's looks like:

Resolving module name '@shared' relative to base url 'D:/apps/my-app/src' - 'D:/apps/my-app/src/@shared'.

After i changed alias to 'shared' and set baseUrl everything starts to work:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "baseUrl": "../",
    "outDir": "../../build/backend"
  },
  "extends": "../../configs/tsconfig.base.json",
  "references": [
    {
      "path": "../shared"
    }
  ],
  "paths": { "shared": ["shared/index"] }
}

OMG I figure it out finally. The baseUrl and paths should be inside the compilerOptions and not outside!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM