This repository describes how to migrate from CommonJS (CJS) to ES Modules (ESM) with Sequelize. The related resource is shown below.
The content of CJS version models/index.js (models/index.js generated by executing the sequelize init
command) is shown below.
Click to go to models-cjs/index.js
An example of model definition is shown below.
Click to go to models-cjs/article.js
An example of use is shown below.
The content of ESM version models/index.mjs is shown below.
Click to go to models-esm/index.mjs
The points are shown below.
- Statically import the model definition function. In the case of CJS, since
require
is not async, model definitions can be imported dynamically. In the case of ESM, On the other hand, sinceimport
is async, model definitions must be imported statically. - Create an instance of Sequelize with environment variables. This point is not necessary for migration to ESM, but it is convenient for containerization, so I have changed it.
- Create an instance of the model by calling a model definition function.
- Call the model's associate function to create an association.
- Export the models.
An example of model definition is shown below.
Click to go to models-esm/article.mjs
The changes are as follows.
- Before:
module.exports =
- After:
export default
An example of use is shown below.
The changes are as follows.
- Before:
const models = require('./models')
- After:
import models from './models/index.mjs'
The SQL statement issued by executing the CJS or ESM source code is shown below. Of course, there is no difference in the content. Only the CREATE and INSERT statements are excerpted.
CREATE TABLE IF NOT EXISTS `users` (
`id` INTEGER NOT NULL auto_increment ,
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `articles` (
`id` INTEGER NOT NULL auto_increment ,
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
`userId` INTEGER NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
ON DELETE NO ACTION
ON UPDATE CASCADE
) ENGINE=InnoDB;
The command examples for outputting the execution result are as follows.
# CJS
node main-cjs.js
# ESM
DB_URL=mysql://tech_blog_user:tech_blog_pass@localhost:3306/tech_blog_db \
node main-esm.js
Since the model definition is statically imported in ESM's models/index.mjs, it is necessary to update index.mjs every time a new model definition file is added, which is inconvenient compared to CJS. If you know a good way, I would appreciate your guidance and comments. Thank you for reading!