Typescript: `import 'constants' ` always resolving to the node 'constants' module

Created on 5 May 2020  ·  7Comments  ·  Source: microsoft/TypeScript




  • VSCode Version:
Version: 1.44.2
Commit: ff915844119ce9485abfe8aa9076ec76b5300ddd
Date: 2020-04-16T17:07:18.473Z (2 wks ago)
Electron: 7.1.11
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Darwin x64 19.3.0
  • OS Version: macOS Catalina 10.15.3 (19D76)

Steps to Reproduce:

  1. Open VSCode.
  2. Create a file src/constants.js exporting foo
  3. Import foo as import { foo } from 'constants'
  4. Hover over the constants file path.
  5. See the following.
module "constants"
@deprecated — since v6.3.0 - use constants property exposed by the relevant module instead.
  1. ⌘ + click on constants file path.
  2. See there are 2 definitions – constants.d.ts and index.d.ts but no src/constants.js

Expected result:

  • see the definition of foo from src/constants

The same issue occurs when using foo for the first time in a module, no import suggestion is shown.

My jsconfig.json file

{
  "compilerOptions": {
    "baseUrl": "./src",
    "jsx": "preserve",
    "module": "es6",
    "moduleResolution": "node",
    "target": "es6"
  },
  "exclude": [
    "**/node_modules/*",
    "coverage",
    "dist",
    "node_modules"
  ],
  "typeAcquisition": {
    "include": [
      "cypress",
      "jest"
    ]
  }
}


Does this issue occur when all extensions are disabled?: Yes/No

Working as Intended

All 7 comments

With "moduleResolution": "node" you must use import { foo } from "./constants" to reference relative modules.

Change your import to be relative or use "moduleResolution": "classic" to get browser style module resolution algorithm.

Hey @yume-chan! Thank you for the reply! I believe I tried this but to no avail. 😭 I’ve seen this issue in a TypeScript project as well but I haven’t tried your suggestion there yet

I believe this is the expected behavior if you have the node typings installed, but someone on TS would have to confirm that. Note that if run the script in node, require('constants') also always resolves to the node constants module and not the local constant.js file.

I do see the expected local constants.js file being resolved if I use a relative import: './constants"

This is the intended behavior

Hey @RyanCavanaugh, that sounds good! How would I go about overriding it to resolve to my local “constants” when working on client code? Importing from “constants/index” doesn’t look as nice 😀 do you recommend simply renaming the folder to something else to avoid all this trouble?

You can add a path mapping

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings