How to create ES module ('.mjs') migration files through sequelize-cli?

77 Views Asked by At

I'm writing PostgreSQL database migrations in my NodeJs project using sequelize-cli and trying to follow ES module syntax in my files.

Unfortunately, I can't find how to enable creation and execution of migrations files of type '.mjs' through sequelize-cli.

I want to configure sequelize such that when I create a migration through command line, the generated migration file should be of type mjs.

I tried adding migrationFileExtension: 'mjs' in config file as suggested by ChatGPT, but it's not working.

FYI, I'm writing migrations in Raw PostgreSQL (only using sequelize's migration functionality).

'use strict';

/** @type {import('sequelize-cli').Migration} */

console.log('in migration file');

export async function up(queryInterface, Sequelize) {
  console.log('up function');
  const createTableQuery = `
    CREATE TABLE users (
      id SERIAL PRIMARY KEY,
      username VARCHAR(50) NOT NULL UNIQUE,
      email VARCHAR(100) NOT NULL UNIQUE,
      password VARCHAR(255) NOT NULL,
      first_name VARCHAR(50) NOT NULL,
      last_name VARCHAR(50) NOT NULL,
      date_of_birth DATE,
      profile_picture_url VARCHAR(255),
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    );
  `;
  
  await queryInterface.sequelize.query(createTableQuery);
}

export async function down(queryInterface, Sequelize) {
  const dropTableQuery = 'DROP TABLE IF EXISTS users;';
  
  await queryInterface.sequelize.query(dropTableQuery);
}

1

There are 1 best solutions below

0
Nazrul Chowdhury On BEST ANSWER

Unfortunately, sequelize-cli doesn't directly support ES modules out of the box for migration files. However, you should still be able to use ES module syntax by employing a workaround.
Set up Babel to transpile your ES module syntax to CommonJS, which sequelize-cli understands.
First Install some necessary packages,

npm install --save-dev @babel/core @babel/cli @babel/preset-env

Create a .babelrc file in your project's root directory with the following configuration,

{
  "presets": [
    "@babel/preset-env"
  ]
}

Write a helper script to execute migrations. This script will be in CommonJS syntax and will call your ES module migration files. Create a file named run-migrations.js

//run-migrations.js file
require('@babel/register')({
  extensions: ['.mjs', '.js'],
})

// Load and execute your sequelize-cli migration script
require('./node_modules/.bin/sequelize-cli db:migrate')

Update your package.json scripts to use the helper script for migration execution.

"scripts": {
  "migrate": "node run-migrations.js"
}

Now, when you run npm run migrate, it will use the Babel-register to transpile your ES module migration files before executing them with sequelize-cli. Make sure to adjust paths and configurations according to your project structure.