I'm working with a NestJS project and I need to use the @octokit/rest library, which is an ES module. However, my project is set up to build in CommonJS. When trying to use the library with require(), I run into an error because the @octokit/rest library doesn't support CommonJS imports.
To solve this, I tried using dynamic import() within a CommonJS environment, but after building the project, the import() is still being compiled in a way that doesn’t work with CommonJS. Here's what I tried:
async createRepository(accessToken: string, repositoryName: string) {
const { Octokit } = await import('@octokit/rest');
const octokit = new Octokit({
auth: accessToken,
});
const response = await octokit.repos.createForAuthenticatedUser({
name: repositoryName,
});
return response.data;
}
Error encountered:
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\...\node_modules\@octokit\rest\dist-src\index.js from C:\Users\...\dist\app.service.js not supported.
How can I ensure that @octokit/rest is imported dynamically in a CommonJS build without causing compatibility issues? Is there a way to make dynamic imports work in this setup, or is there a better approach for using ES modules in a CommonJS project?
for nodejs v22+ you can just use the --experimental-require-module
nodejs flag. So:
nest start -e "node --experimental-require-module"
should be enough
note that Jest doesn't support this flag and so it will fail