cli: models/index.js doesn't work with ES6 modules

What you are doing?

Trying to load models with models/index.js doesn’t work with ES6 modules activated with "type": "module"

const basename = path.basename(__filename);
// {...}
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);

Variables like __filename and __dirname don’t work anymore with modules.

What do you expect to happen?

There should be an option to choose between Modules or CommonJS.

What is actually happening?

There’s only CommonJS support.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 21 (5 by maintainers)

Most upvoted comments

This is my solution for the moment

import { readdirSync } from "fs";
import { basename, dirname } from "path";
import { Sequelize, DataTypes } from "sequelize";
import { fileURLToPath } from 'url';
import database from "../config/database.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const db = {};
const sequelize = new Sequelize(database.development);

export default (async () => {
  const files = readdirSync(__dirname)
    .filter(
      (file) => file.indexOf('.') !== 0
      && file !== basename(__filename)
      && file.slice(-3) === '.js',
    );

  for await (const file of files) {
    const model = await import(`./${file}`);
    const namedModel = model.default(sequelize, DataTypes);
    db[namedModel.name] = namedModel;
  }

  Object.keys(db).forEach((modelName) => {
    if (db[modelName].associate) {
      db[modelName].associate(db);
    }
  });

  db.sequelize = sequelize;
  db.Sequelize = Sequelize;
	
  return db;
})();

For now, I created this temporary solution.

Thanks a lot for your effort. I tried it out and can confirm that it works. Unfortunately I ran into another issue: migrations seem not to work with ES6 modules out of the box. Possible solutions seem quite hacky. I decided to keep using CommonJS syntax and wait until there is better support for ES6.

I write like this but it is’nt load the models and then give my the error: TypeError: model.default is not a function

how can i fix it?