Skip to content

Commit

Permalink
fix: support dynamic require in child_process
Browse files Browse the repository at this point in the history
  • Loading branch information
mrlubos committed Sep 25, 2024
1 parent 4f59e68 commit 0bc1ebe
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 61 deletions.
5 changes: 5 additions & 0 deletions .changeset/moody-ears-talk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hey-api/openapi-ts': patch
---

fix: support dynamic require in child_process
24 changes: 0 additions & 24 deletions packages/openapi-ts/src/generate/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,6 @@ import path from 'node:path';
import { getConfig, isStandaloneClient } from '../utils/config';
import { ensureDirSync } from './utils';

const isESM = () => {
try {
return typeof import.meta.url === 'string';
} catch (error) {
return false;
}
};

const getRequire = async (): Promise<NodeRequire> => {
try {
if (isESM()) {
const module: any = await import('node:module');
const createRequire: (path: string | URL) => NodeRequire =
module.createRequire;
return createRequire(import.meta.url);
}

return module.require;
} catch (error) {
return module.require;
}
};

export const clientModulePath = () => {
const config = getConfig();
return config.client.bundle ? './client' : config.client.name;
Expand Down Expand Up @@ -54,7 +31,6 @@ export const generateClient = async (
const dirPath = path.resolve(outputPath, 'client');
ensureDirSync(dirPath);

const require = await getRequire();
const clientModulePath = path.normalize(require.resolve(moduleName));
const clientModulePathComponents = clientModulePath.split(path.sep);
const clientSrcPath = [
Expand Down
11 changes: 11 additions & 0 deletions packages/openapi-ts/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { defineConfig } from 'tsup';

export default defineConfig((options) => ({
banner(ctx) {
/**
* fix dynamic require in ESM
* @link https://github.com/hey-api/openapi-ts/issues/1079
*/
if (ctx.format === 'esm') {
return {
js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",
};
}
},
clean: true,
dts: true,
entry: ['src/index.ts'],
Expand Down
Loading

0 comments on commit 0bc1ebe

Please sign in to comment.