JumpingElephant
JumpingElephant

Reputation: 161

Babel not allowing imports without .js file extension

I have installed babel and can now use import syntax for example. However, this code import { dbConnect } from './utils/dbConnect.js'; works but this code import { dbConnect } from './utils/dbConnect'; does not work.

I have been searching for hours online, and from what I understand, this functionality should be auto enabled in @babel/preset-env that I already have installed. Here are my dependencies:

"dependencies": {
    "@babel/core": "^7.14.6",
    "@babel/node": "^7.14.5",
    "@babel/preset-env": "^7.14.5",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "mongoose": "^5.12.14",
    "nodemon": "^2.0.7"
  },
  "devDependencies": {
    "eslint": "^7.28.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-plugin-import": "^2.23.4"
  }

I currently do not have a .babelrc file.

Here is the error:

internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/me/Repositories/myrepo/server/utils/dbConnect' imported from /Users/me/Repositories/myrepo/server/index.js
Did you mean to import ../utils/dbConnect.js?
    at finalizeResolution (internal/modules/esm/resolve.js:276:11)
    at moduleResolve (internal/modules/esm/resolve.js:699:10)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
    at Loader.resolve (internal/modules/esm/loader.js:88:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:241:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:56:40)
    at link (internal/modules/esm/module_job.js:55:36) {
  code: 'ERR_MODULE_NOT_FOUND'

Upvotes: 4

Views: 3677

Answers (2)

JumpingElephant
JumpingElephant

Reputation: 161

I ended up enabling imports without file extension with the following: --experimental-modules --es-module-specifier-resolution=node added to the node while running my app.

My start script is now: "start": "nodemon --exec babel-node --require dotenv/config --experimental-modules --es-module-specifier-resolution=node index.js"

Upvotes: 6

loganfsmyth
loganfsmyth

Reputation: 161517

If you use Node's builtin ES module support via "type": "module" or .mjs then you are opting into more restrictive requirements. Node requires you to explicitly provide file extensions as part of that.

Babel's official plugins don't have any logic to add extensions, since that's not really related to ECMAScript as a language/specification. You could consider user a community plugin like https://www.npmjs.com/package/babel-plugin-add-import-extension, which appears to support what you're looking for.

Upvotes: 3

Related Questions