javascriptnode.jsvisual-studio-code

VS Code is not including .js after doing an auto import


When working with NodeJS in VS Code, I've had issues where the auto-import function of VS Code wouldn't include the .js extension as required by the Node module system.

For example:

// As required by Node
import { foo } from './foo.js'

// As added by VS Code
import { foo } from './foo'

When left as specified by VS Code, I get the following error:

node:internal/process/esm_loader:91
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '\mbot\util\strings' imported from \mbot\index.js
Did you mean to import ../util/strings.js?
    at new NodeError (node:internal/errors:372:5)
    at finalizeResolution (node:internal/modules/esm/resolve:405:11)
    at moduleResolve (node:internal/modules/esm/resolve:966:10)
    at defaultResolve (node:internal/modules/esm/resolve:1176:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:605:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:318:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
    at link (node:internal/modules/esm/module_job:78:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Solution

  • This can be solved by adding a jsconfig.json file to your project root. Specifically by including at least the following, my project started auto-importing with the .js file extension as required by NodeJS.

    jsconfig.json

    {
      "compilerOptions": {
        "moduleResolution": "nodenext", // <- Necessary to get imports with .js
      },
      "exclude": ["node_modules"]
    }
    

    Note: VS Code will complain about the nodenext value requiring a special package, but it works fine without it.