Skip to content

Commit b525011

Browse files
committed
feat: implement loadModule utility for dynamic module loading (1.5.2)
1 parent 35bd982 commit b525011

4 files changed

Lines changed: 19 additions & 4 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "dapir",
3-
"version": "1.5.1",
3+
"version": "1.5.2",
44
"type": "module",
55
"description": "An api wrapper",
66
"source": "src/index.ts",

‎src/Server.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import log from './utils/log';
33
import { WebSocket, WebSocketServer } from 'ws';
44
import { Server as HttpServer, IncomingMessage as HttpIncomingMessage, ServerResponse as HttpServerResponse } from 'http';
55
import indexFolder from './utils/indexFolder';
6+
import loadModule from './utils/loadModule';
67
import { OpenAPIV3_1 as OpenAPI } from 'openapi-types';
78
import Documentation from './documentation';
89
import { HTTPContext, RouteFile, RouteConfig, RouteAuthenticationMethodWithData } from './types/httprouter';
@@ -139,7 +140,7 @@ export class Server<
139140
for (const file of filteredDocFiles) {
140141
if (file.directory) continue;
141142

142-
const imported = await import(file.fullPath);
143+
const imported = await loadModule(file.fullPath);
143144
if (!imported) continue;
144145

145146
const doc = imported as OASchemaFile;
@@ -182,7 +183,7 @@ export class Server<
182183
for (const file of filteredRoutes) {
183184
if (file.directory) continue;
184185

185-
const imported = await import(file.fullPath);
186+
const imported = await loadModule(file.fullPath);
186187
if (!imported) continue;
187188

188189
// Apparently the bundler has no clue wtf "this" is when used like "this.routeHandler<HTTPContext>"

‎src/utils/loadModule.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { createRequire } from 'module';
2+
import { pathToFileURL } from 'url';
3+
4+
export default async function loadModule(fullPath: string): Promise<unknown> {
5+
try {
6+
return await import(pathToFileURL(fullPath).href);
7+
} catch (error) {
8+
const code = (error as NodeJS.ErrnoException).code;
9+
if (code == 'ERR_UNKNOWN_FILE_EXTENSION' || code == 'ERR_UNSUPPORTED_ESM_URL_SCHEME') {
10+
return createRequire(pathToFileURL(fullPath))(fullPath);
11+
}
12+
throw error;
13+
}
14+
}

‎tsup.config.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@ export default defineConfig({
1010
return { js: format === 'cjs' ? '.cjs' : '.modern.js' };
1111
},
1212
sourcemap: false,
13-
});
13+
});

0 commit comments

Comments
 (0)