seppevs / migrate-mongo

A database migration tool for MongoDB in Node
MIT License
902 stars 160 forks source link

SyntaxError: Unexpected token 'export' #417

Open joezappie opened 2 years ago

joezappie commented 2 years ago

Describe the bug I am getting an error about using import in a project that uses ESM.

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.require (/workspaces/mrp/node_modules/migrate-mongo/lib/utils/module-loader.js:3:12)
    at Object.loadMigration (/workspaces/mrp/node_modules/migrate-mongo/lib/env/migrationsDir.js:101:27) {
  migrated: []
}

I see line 101 in migrationsDir is doing a require thats surrounded by a try catch. Doesn't seem like e.code === ERR_REQUIRE_ESM as its not running that and rethrowing the error.

try {
      return moduleLoader.require(migrationPath);
    } catch (e) {
      if (e.code === 'ERR_REQUIRE_ESM') {
        return moduleLoader.import(url.pathToFileURL(migrationPath));
      }
      throw e;
    }

Since it seems like the moduleSystem config variable was recently added, how about using that instead of a try catch to run the appropriate loader?

const configContent = await config.read();
switch(configContent.moduleSystem) {
   case "esm":
      return moduleLoader.import(url.pathToFileURL(migrationPath));
      break;
   case "commonjs":
      return moduleLoader.require(migrationPath);
      break;
}

To Reproduce I am using this via the programmable API.

migrate.config.set(this.config);
const { db, client } = await migrate.database.connect();
await migrate.up(db, client);

Expected behavior Should properly import when in esm environment.

Additional context I am running this as a bin script. Package.json is set to type module and my config file for migrate-mongo has moduleSystem: 'esm'.

deiay commented 1 year ago

I'm having the same issue

lukjaki commented 9 months ago

I'm experiencing similar issue.

onurcskun commented 7 months ago

I'm having the same issue as well.

a-warner-knight commented 3 weeks ago

I had the same issue when running from a quick and dirty docker image based on node-20, with migrate-mongo installed globally running the raw scripts, rather than from within a package. I worked around it by changing the migrate-mongo-config.js and migrations/* scripts to be non-esm.

In migrate-mongo-config.js:

In scripts:

Hope that helps someone looking for a quick fix.