-
Notifications
You must be signed in to change notification settings - Fork 752
Description
Extension Version
0.20251205.1
VS Code Version
1.106.3
Operating system Version
macOS Tahoe 26.1
Steps to reproduce
- Clone https://github.com/gebsh/auto-import-cjs.
- Open the cloned repository in VS Code.
- Open the file
main1.jsormain2.js, typeLIBand choose theLIB_VERSIONimport from./libfrom the import suggestions.
Issue
In a JavaScript project that uses the .js extension for all files and has type: "commonjs" set in package.json, TypeScript auto-imports items via the import statement when module is set to node16, node18, or node20. For example, using this setup:
// tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"module": "node20",
"checkJs": true,
"noEmit": true
}
}// lib.js
module.exports = { LIB_VERSION: 1 };// main.js
module.exports.foo = 0;When I try to auto-import LIB_VERSION in main.js, it's inserted as:
import { LIB_VERSION } from "./lib";which is invalid syntax for a CJS file. I'd expect it to be imported via require(), since the module type of this file can be inferred from package.json.
Explicitly setting moduleDetection to auto fixes this but only if the file where I'm auto-importing an item already has CJS syntax. In empty files, the auto-import still uses the import syntax. Surprisingly, changing the file extensions to .cjs makes it even worse, because then the moduleDetection workaround doesn't work at all. It's possible to delete the module setting altogether, which fixes the problem in both empty files and files with CJS syntax, but AFAIU the TypeScript's module settings, I'm supposed to use nodeXX as that code is run in Node.
This happens in both TypeScript 5.9 and TypeScript Native. I'm reporting this here as per microsoft/TypeScript#62827.
I did a bit of debugging in TS 5.9, and AFAICT this is caused because node20 implicitly sets moduleDetection to force, which in turn switches useRequire in the auto-import code to false. That implicit switch to force is surprising, considering the documentation of moduleDetection:
There are three choices:
"auto"(default) - TypeScript will not only look for import and export statements, but it will also check whether the"type"field in apackage.jsonis set to"module"when running with module:nodenextornode16
but I assume the documentation might be outdated/incorrect as it also lacks node18 and node20.