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
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
LoadConfigResult,
} from './types.js';

export { setJitiLoader } from './jiti.js';
export { withConfigMeta } from './meta.js';
export type {
ConfigDefinition,
Expand Down
15 changes: 13 additions & 2 deletions src/jiti.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@ import { cachedImport } from './cachedImport.js';
import { getConfigExport } from './helpers.js';
import type { ConfigDefinition, LoadedConfig } from './types.js';

const getJiti = cachedImport(() => import('jiti'));
// Keep the injection API independent of the optional jiti package's types.
type JitiLoader = () => Promise<{ createJiti: unknown }>;

let getJiti: JitiLoader = cachedImport(() => import('jiti'));

/**
* Set the lazy jiti importer for this module instance before loading configs.
* Replaces the cached import without invoking the new importer.
*/
export const setJitiLoader = (loader: JitiLoader): void => {
getJiti = cachedImport(loader);
};

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

try {
({ createJiti } = await getJiti());
({ createJiti } = (await getJiti()) as typeof import('jiti'));
} catch (error) {
throw new Error(
'The "jiti" package is required to load this config. Install it with your package manager.',
Expand Down
24 changes: 24 additions & 0 deletions tests/loader-jiti/injection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { afterEach, expect, rstest, test } from 'rstack/test';
import { loadConfig, setJitiLoader } from '../../src/index';

afterEach(() => {
setJitiLoader(() => import('jiti'));
});

test('lazily imports injected jiti once for concurrent configs', async () => {
const importer = rstest.fn(() => import('jiti'));
setJitiLoader(importer);
expect(importer).not.toHaveBeenCalled();

const options = {
cwd: import.meta.dirname,
path: 'demo.config.ts',
loader: 'jiti',
} as const;
const [result] = await Promise.all([
loadConfig(options),
loadConfig(options),
]);
expect(result.content).toEqual({ loader: 'jiti' });
expect(importer).toHaveBeenCalledTimes(1);
});
Loading