Module Prioritization in WebStorm
WebStorm prioritizes the individual file's module type over the project-level settings when generating automatic imports. The IDE determines the module system based on the following hierarchy:
- File Extension:
.mjs files are treated as ESM; .cjs files are treated as CommonJS.
- Package Configuration: If the extension is
.js or .ts, the IDE looks for the nearest package.json containing "type": "module" (ESM) or "type": "commonjs" (CJS).
- TypeScript Configuration: The
module and moduleResolution settings in tsconfig.json guide the language server, but the file's perceived identity usually dictates whether the IDE suggests import or require().
Explanation of Inconsistent Suggestions
In mixed environments, inconsistency typically occurs because the IDE is attempting to maintain runtime compatibility. If a file is identified as CommonJS, WebStorm will suggest require() because import statements are syntactically invalid in CJS files (unless using dynamic import()). Conversely, in ESM files, require is not defined, forcing the IDE to suggest import.
When a symbol is available in both formats (a "dual package"), the IDE may alternate suggestions if the tsconfig.json resolution strategy (e.g., Node16 or NodeNext) is not strictly aligned with the actual file extensions used in the project.
Enforcing a Specific Import Style
To reduce inconsistency and enforce a specific style, adjust the following settings:
- Configure TypeScript Resolution: In
tsconfig.json, set "moduleResolution": "NodeNext" or "Node16". This forces the IDE to respect the package.json type field and file extensions more strictly.
- IDE Preferences: Navigate to
Settings > Editor > Code Style > TypeScript (or JavaScript). Under the Imports tab, ensure that "Use imports instead of require" is checked. Note that this will only apply to files the IDE recognizes as ESM.
- Explicit Extensions: Use
.mts/.mjs for ESM and .cts/.cjs for CommonJS to remove ambiguity for the IDE's static analysis.
Verification Command
To verify which module system Node.js is applying to a specific file (which should mirror the IDE's behavior), you can run a simple check for the require global:
node -e "try { console.log(typeof require); } catch (e) { console.log('ESM Environment'); }"
Diagnostic Detail Needed: To provide a more specific configuration, please specify the moduleResolution value currently defined in your tsconfig.json.