Sequelize配合@babel/register使用迁移ES语法时报ERR_REQUIRE_ESM错误
问题核心根因
- 触发
ERR_REQUIRE_ESM的本质矛盾是:package.json中开启了"type": "module"后,Node.js会全局将项目内的.js文件默认识别为ES模块;但Sequelize CLI的核心加载逻辑仍基于CommonJS的require方法,遇到原生ESM文件时会直接抛出错误 - 原配置中
@babel/register失效的原因是:Node在开启ESM模式后,CommonJS侧的转译钩子(@babel/register实现的就是CommonJS模块加载时的转译拦截)无法拦截被标记为ESM规则的文件转译流程;同时@babel/preset-env未指定转译输出格式,在ESM模式下会默认保留ES模块语法,没有编译成可被require加载的CommonJS代码
分步调整配置
1. 修正Babel转译规则
修改.babelrc配置,明确指定转译目标为当前Node版本、输出格式为CommonJS,避免默认保留ESM语法:
{ "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" }, "modules": "commonjs" } ] ] }
2. 调整.sequelizerc加载逻辑
修改.sequelizerc配置,明确@babel/register的转译覆盖范围,确保在CLI加载迁移、模型、种子文件之前就完成转译钩子注册:
// 该文件由Sequelize CLI通过require直接加载,保持CommonJS写法即可 require('@babel/register')({ extensions: ['.js'], // 明确指定需要转译的目录范围 only: [ './migrations/**/*.js', './seeders/**/*.js', './models/**/*.js', './constants/**/*.js' ] }); require('@babel/polyfill'); const path = require('path'); module.exports = { 'config': path.resolve('config', 'config.json'), 'models-path': path.resolve('models'), 'seeders-path': path.resolve('seeders'), 'migrations-path': path.resolve('migrations') }
3. 修正迁移文件的语法混写问题
原迁移文件同时混用了ESM的import语法和CommonJS的module.exports导出写法,需要统一为ES模块导出规则,适配Babel转译流程;同时修复枚举值的传参bug:
'use strict'; import { TABLE_NAMES, REQUEST_STATUS } from '../constants'; export default { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('Requests', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER, }, message: { type: Sequelize.TEXT, }, // 修正原写法的嵌套数组问题:原写法传了二维数组作为枚举参数 status: { type: Sequelize.ENUM(...Object.values(REQUEST_STATUS)), }, requested_time: { type: Sequelize.DATE, }, requested_by_id: { type: Sequelize.INTEGER, references: { model: TABLE_NAMES.USERS, key: 'id', }, }, requested_to_id: { type: Sequelize.INTEGER, references: { model: TABLE_NAMES.USERS, key: 'id', }, }, reject_response: { type: Sequelize.TEXT, }, response_time: { type: Sequelize.DATE, allowNull: true, }, type: { type: Sequelize.STRING, }, createdAt: { allowNull: false, type: Sequelize.DATE, }, updatedAt: { allowNull: false, type: Sequelize.DATE, }, }); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable('Requests'); }, };
关键注意事项
- 不要为了适配CLI把
package.json里的"type": "module"改回"commonjs",否则会导致原有业务代码里的ESM import写法触发Node报错 - 不要将迁移、种子文件的后缀改为
.mjs,否则Sequelize CLI会直接走Node原生ESM加载逻辑,跳过Babel转译流程 - 直接在
package.json的scripts块中添加CLI执行命令即可,无需额外修改启动参数:
"scripts": { // ... 原有其他脚本 "db:migrate": "sequelize-cli db:migrate", "db:migrate:undo": "sequelize-cli db:migrate:undo:all" }
内容的提问来源于stack exchange,提问作者mdanishs
相关产品推荐
相关产品推荐

