javascript umzug无法导入节点js中的ES模块

mnemlml8  于 2023-10-14  发布在  Java
关注(0)|答案(2)|浏览(119)

我试图建立一个简单的应用程序作为我的个人项目使用JavaScript。我正在使用sequelize ORM来处理数据库更改。现在我想回滚迁移,为此我使用了以下命令npx sequelize-cli db:migrate:undo当我运行上述命令时,我遇到了以下错误。

下面是我的package.json文件的内容。

{
  "name": "poc",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "mysql2": "^3.6.1",
    "sequelize": "^6.33.0"
  },
  "type":"module",
  "devDependencies": {
    "sequelize-cli": "^6.6.1"
  }
}

下面是我的序列化迁移文件的内容。

'use strict';

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

export default {
  async up (queryInterface, Sequelize) {
    /**
     * Add altering commands here.
     *
     * Example:
     * await queryInterface.createTable('users', { id: Sequelize.INTEGER });
     */
    queryInterface.addColumn('Users','deletedAt', {
      type: Sequelize.TIME
    })
  },

  async down (queryInterface, Sequelize) {
    /**
     * Add reverting commands here.
     *
     * Example:
     * await queryInterface.dropTable('users');
     */
    queryInterface.removeColumn('Users','deletedAt')
  }
};

我想在我的项目中使用ES6模块和语法。提前感谢我将得到的所有帮助。

cgvd09ve

cgvd09ve1#

将Sequelize迁移文件扩展名从.js更改为.mjs,并在主脚本中定义自定义解析器。
有关更多信息,我遵循了这里的示例(查看.README是怎么说的):https://github.com/sequelize/umzug/tree/main/examples/2.es-modules

djmepvbi

djmepvbi2#

你只需要在示例化Umzug时使用resole函数,这样你就可以使用import而不是让Umzug使用require

import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));

const sequelize = new Sequelize(...);

export const migrator = new Umzug({
  migrations: {
    glob: ['migrations/*.{ts,js}', { cwd: __dirname }],
    resolve: params => {
      const getModule = () => import(params.path!);
      return {
        // adjust the parameters Umzug will
        // pass to migration methods when called
        name: params.name,
        up: async (params) => (await getModule()).up(params),
        down: async (params) => (await getModule()).down(params),
      };
    }
  },
  context: sequelize,
  storage: new SequelizeStorage({
    sequelize,
  }),
  logger: console,
});

相关问题