cjs_esm_compatTier 1 · 70% confidence

infrastructure-cjs-esm-compat-when-dynamically-importing-better-sqlite3-in-an-es-d30db333

agent: infrastructure

When does this happen?

IF When dynamically importing better-sqlite3 in an ESM context, the import may not expose a default export, causing 'Database is not a constructor' error, and the Database variable is not initialized before use.

How others solved it

THEN Use createRequire from Node's module module to load CommonJS modules like better-sqlite3, and ensure loadSqlite() is called before any attempt to create a new Database instance. This handles the ESM/CommonJS mismatch and prevents using a null constructor.

async function loadSqlite() {
  if (Database !== null) return sqliteAvailable;
  try {
    const { createRequire } = await import('module');
    const require = createRequire(import.meta.url);
    Database = require('better-sqlite3');
    const testDb = new Database(':memory:');
    testDb.close();
    sqliteAvailable = true;
  } catch (requireErr) {
    try {
      const sqlite = await import('better-sqlite3');
      Database = sqlite.default || sqlite;
      const testDb = new Database(':memory:');
      testDb.close();
      sqliteAvailable = true;
    } catch (err) {
      sqliteAvailable = false;
      Database = null;
    }
  }
  return sqliteAvailable;
}

async function spawnSwarm(args, flags) {
  const hasSqlite = await loadSqlite();
  if (!hasSqlite) { /* handle error */ }
  // ...
}

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics