1

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
    Any circular dependencies between your modules? It looks a bit like what should be a temporal dead zone error. – Bergi Jan 02 '23 at 12:43

0 Answers0