Nodejs Babel TypeError: Cannot read properties of undefined (reading 'default')

588 views Asked by At

I'm using babel to transpile es6 code to es5. I have this mongoose model

// src/user.model
const User = mongoose.model('User', userSchema);

export default User;

used in this index.js file within the same folder

// src/index.js
import User from "./user.model";

export {User};

On build it generates this error

return _user["default"];
                ^
TypeError: Cannot read properties of undefined (reading 'default')

The full compiled code is

// build/index.js
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "User", {
  enumerable: true,
  get: function get() {
    return _user["default"];
  }
});
var _user = _interopRequireDefault(require("./user.model"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

As you can see the _user variable is initialized after it was referenced.

When I tweak this compiled code and initialize the _user variable before it is used, the error goes. Is there something I can do to prevent babel from initializing variables before it is called?

1

There are 1 answers

0
Ryan Shillington On

I had this error message but my problem was a circular dependency. Essentially I had something like this:

Contents of a.js:

import B from './b';
import C from './c';

export default function A() {
    C();
}

Contents of b.js:

import A from './a';

export const SOME_CONSTANT = {
   whatever: A(),
};

The problem is that Node is still trying to initialize a.js, and in doing so it got one of it's functions called before importing C. Specifically it's functions got called while importing B.

My fix was to re-order the imports in a.js:

import C from './c';
import B from './b';

export default function A() {
    C();
}