Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/cachedImport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/** Share the pending import while allowing a failed import to be retried. */
export const cachedImport = <T>(
importer: () => Promise<T>,
): (() => Promise<T>) => {
let promise: Promise<T> | undefined;

return () =>
(promise ??= importer().catch((error: unknown) => {
promise = undefined;
throw error;
}));
};
5 changes: 4 additions & 1 deletion src/jiti.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { cachedImport } from './cachedImport.js';
import { getConfigExport } from './helpers.js';
import type { ConfigDefinition, LoadedConfig } from './types.js';

const getJiti = cachedImport(() => import('jiti'));

export const loadWithJiti = async <Config, Params extends unknown[]>(
configPath: string,
exportName: string | false,
Expand All @@ -9,7 +12,7 @@ export const loadWithJiti = async <Config, Params extends unknown[]>(
let createJiti: (typeof import('jiti'))['createJiti'];

try {
({ createJiti } = await import('jiti'));
({ createJiti } = await getJiti());
} catch (error) {
throw new Error(
'The "jiti" package is required to load this config. Install it with your package manager.',
Expand Down
10 changes: 6 additions & 4 deletions src/native.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { pathToFileURL } from 'node:url';
import { cachedImport } from './cachedImport.js';

const getFreshImport = cachedImport(
() => import(/* rspackChunkName: 'freshImport' */ 'fresh-import'),
);

type NativeLoadResult = {
configModule: unknown;
Expand All @@ -21,10 +26,7 @@ export const loadWithNative = async (
};
}

const { freshImport } = await import(
/* rspackChunkName: 'freshImport' */
'fresh-import'
);
const { freshImport } = await getFreshImport();
const freshImportResult = await freshImport(configFileURL);

if (freshImportResult) {
Expand Down
Loading