standard-things / esm

Tomorrow's ECMAScript modules today!
Other
5.27k stars 147 forks source link

Error while importing ES Module in commonjs via Dynamic import #920

Open testgitdl opened 2 years ago

testgitdl commented 2 years ago

We have an inhouse developed module that we need to use in a commonjs project. In case in main.page.ts we import login.page than an "Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:_AutomationProjects\CTA\Playwright\dist\page-objects\esm2020\lib\login.page' imported from C:_AutomationProjects\CTA\Playwright\dist\page-objects\esm2020\lib\main.page.mjs" appears. It appears that dynamic import is not working in this case..otherwise no problem

Contents of the inhouse developed module:

login.page.ts

export class LoginPage {
  public page: Page;
  constructor(page: Page) {
    this.page = page;
  }
}

main.page.ts

import { LoginPage } from "./login.page";

export class MainPage {
  public page: Page;
  public login: LoginPage;
  constructor(page: Page) {
    this.page = page;
    this.login = new LoginPage(page);
  }
}

Then this project is installed in another one that is commonjs and to use it we make use on dynamic imports

main.cjs

mainPage = new (await import('../../dist/page-objects/esm2020/lib/main.page.mjs')).MainPage(page);

If in main.page.ts we remove the login.page import that everything is working.

How can we import es modules in commonjs in this case? Cannot move away from commonjs as the test tool does not know how to handle ESM