TypeScript: Imports in index.ts file are not getting correctly resolved.

"typescript": "3.2.2"

Imports in index.ts file are not getting correctly imported. Inside engine folder, I have files as

  • engine
    • index.ts
    • engine.ts
    • test.ts

Inside index.ts, I have

export { Engine } from ‘./engine’; export { Test } from ‘./test’;

When I try to import, Engine class in another file using import {Engine} from ‘…/engine’; engine is not defined

I get it correct if I write this way. import {Engine} from '../engine/engine'; This was working fine previously, but after resent ts version upgrade it is giving this error.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 22 (3 by maintainers)

Most upvoted comments

try setting "moduleResolution": "node" in compilerOptions of your tsconfig.json

You have to add a slash in the folder (module) name, this will treat index.ts as the folder index.

import {Engine} from '../engine/';

Any recommendations available for writing exports in index.ts and using the exported modules internnally ? … this issue is really frustrating to debug : (…

I’m having a similar issue when using baseUrl: "src"

Obs: the error is shown when the file is open, but the code runs smoothly. The import actually works. Maybe VSCode TS intellisense is the one to blame here.

Project structure:

constants
  foo.ts
  bar.ts
  index.ts // Re-exports from foo and bar
  xxx.ts // Re-exports from foo and bar (to test the behavior)

other-folder
  component.tsx  // Trying to import from 'constants'

Test results from component.tsx

import { FOO } from 'constants';  // ERROR
import { FOO } from 'constants/xxx';  // WORKS
import { FOO } from '../constants';  // WORKS
import { FOO } from 'constants/foo';  // WORKS

This is the error:

image

This is my tsconfig.json file:

TS version: "typescript": "^4.5.5"

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": "src",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["dom", "dom.iterable", "esnext"],
    "noEmit": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
  },
  "exclude": [
    "node_modules",
  ]
}

Obs: This is happening inside my packages/admin project. This is a monorepo using Yarn workspaces. Not sure if this is related or not. TypeScript is installed at the root of the workspace (but I think this error is coming from VSCode TS itself).

You have to add a slash in the folder (module) name, this will treat index.ts as the folder index.

import {Engine} from '../engine/';

@coderbuzz first of all, thank you. You’ve saved my sanity.

Second of all, are there docs/is this common knowledge/where is this learned if you had not been here? I certainly didn’t see it in module resolution docs.