Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sequelize-cli in Node 14 with type: module

I'm trying to set up the project using Node v14.3 and sequelize.

I don't want to use babel-register. Instead of this I set "type": "module" in my package.json and use all ES6 - ES11 features out of the box.

I also want to use sequelize-cli for setting up and applying migrations. Everything works except the following command:

& sequelize db:migrate

Sequelize CLI [Node: 14.3.0, CLI: 5.5.1, ORM: 5.21.11]

Loaded configuration file "config/config.json".
Using environment "development".
== 20200530214311-create-user: migrating =======

ERROR: Must use import to load ES Module: /home/kasheftin/work/tests/chai-http-publication/migrations/20200530214311-create-user.js
require() of ES modules is not supported.
require() of /home/kasheftin/work/tests/chai-http-publication/migrations/20200530214311-create-user.js from /home/kasheftin/.nvm/versions/node/v14.3.0/lib/node_modules/sequelize-cli/node_modules/umzug/lib/migration.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename 20200530214311-create-user.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/kasheftin/work/tests/chai-http-publication/package.json.

We see that under the hood sequelize-cli uses require(). That's not allowed for ES Module. It suggests 3 ways to solve this:

  • rename 20200530214311-create-user.js to end in .cjs - Can not be done, sequelize-cli does not find migrations that end with .cjs.

  • Change the requiring code to use import() - I don't want to touch sequelize-cli code.

  • Remove "type": "module" - I can not because everything stops working.

Is there any other way to make sequelize-cli work? I'm using tests heavily and I want the test database to be prepared automatically before running tests.

like image 777
Kasheftin Avatar asked May 31 '20 19:05

Kasheftin


1 Answers

A solution is to add a package.json in your migrations folder to override the type: "module" from your main package.json

This package.json would look like this:

{
  "type": "commonjs"
}

and your migration file have to look like this:

module.exports = {
  up: async (queryInterface, Sequelize) => {

  },

  down: async (queryInterface, Sequelize) => {

  }
};

It works well with nodeJS 14.16.1 & Sequelize 6.6.2 & sequelize-cli 6.2.0

like image 191
Hugo LARROUSSE Avatar answered Sep 18 '22 13:09

Hugo LARROUSSE