Rayrun
← Back to Discord Forum

Error: require() of ES Module

Hello! I'm trying to import a function from a file, but I'm getting this error:

Instead change the require of index.js in /Users/paolotiu/Desktop/code/work/gibki/taikee/packages/db/src/index.ts to a dynamic import() which is available in all CommonJS modules.

My project is in a monorepo using turborepo and pnpm.

I'm importing from apps/web/tests/db.ts the file is located in packages/db/src/index.ts

Here's the source code:

// db/src/index.ts
import { s } from "./schema";
import { Config, cast, connect } from "@planetscale/database";
import { DrizzleConfig } from "drizzle-orm";
import { drizzle } from "drizzle-orm/planetscale-serverless";

export * from "./schema";
export * from "./zod";

export const createPlanetscaleDb = (
  config: Config,
  opts?: {
    /**
     * If true, will cache the database connection
     * Does not work with cloudflare workers
     */
    withCache?: boolean;
  } & Omit<DrizzleConfig<any>, "schema">,
) => {
  const connection = connect({
    ...config,
    fetch: config.fetch
  });

  return drizzle(connection as any, {
    schema: s,
    logger: opts?.logger,
  });
};

export type Database = ReturnType<typeof createPlanetscaleDb>;
// db.ts
import { IS_DEV } from "../../app/utils/constants";
import type { DB } from "../../app/utils/db/db.server";
import { createPlanetscaleDb } from "db";

export const createDb = (env: any): DB => {
  return createPlanetscaleDb(
    {
      host: env.DATABASE_HOST as string,
      username: env.DATABASE_USERNAME as string,
      password: env.DATABASE_PASSWORD as string,
    },
    {
      logger: IS_DEV,
    }
  );
};

This thread is trying to answer question "How to resolve the 'Error: require() of ES Module' when trying to import a function from a file in a monorepo using turborepo and pnpm?"

1 reply

Fixed this by setting type: "module" of apps/web in package.json. It was a remix project so I had to edit remix.config.js to use export default instead of module.exports.

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].