From dd46217efdfd762038f85de6e5b98e13421bd0ec Mon Sep 17 00:00:00 2001 From: ryoppippi <1560508+ryoppippi@users.noreply.github.com> Date: Sun, 14 Jul 2024 23:43:32 +0100 Subject: [PATCH] feat: add dynamicImport utility function (fixes: fixes: #198) This commit introduces a new utility function, dynamicImport, which is used to dynamically import modules. This function is now used in the Svelte language file to import the Svelte compiler. This change improves the code readability and maintainability. --- packages/unplugin-typia/src/core/languages/svelte.ts | 3 ++- packages/unplugin-typia/src/core/utils.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/unplugin-typia/src/core/languages/svelte.ts b/packages/unplugin-typia/src/core/languages/svelte.ts index 204d392e..e562bfcb 100644 --- a/packages/unplugin-typia/src/core/languages/svelte.ts +++ b/packages/unplugin-typia/src/core/languages/svelte.ts @@ -1,5 +1,6 @@ import type { Data, ID, Source } from '../types.js'; import { wrap } from '../types.js'; +import { dynamicImport } from '../utils.js'; /** * Check if a file is a Svelte file. @@ -23,7 +24,7 @@ export async function preprocess( { source, id, transform }: { source: Source; id: ID; transform: TransformFunction }, ): Promise<{ code: Data }> { - const { preprocess: sveltePreprocess } = await import('svelte/compiler'); + const { preprocess: sveltePreprocess } = await dynamicImport('svelte/compiler') as typeof import('svelte/compiler'); const { code } = await sveltePreprocess(source, { script: async ({ content, filename, attributes }) => { if (filename == null) { diff --git a/packages/unplugin-typia/src/core/utils.ts b/packages/unplugin-typia/src/core/utils.ts index 496061ce..10354f74 100644 --- a/packages/unplugin-typia/src/core/utils.ts +++ b/packages/unplugin-typia/src/core/utils.ts @@ -10,3 +10,11 @@ export function log( export function isBun() { return globalThis.Bun != null; } + +/** + * Dynamic import a module. + * Because JSR fails to resolve dynamic import, we have to use this workaround. (see: https://github.com/ryoppippi/unplugin-typia/issues/198) + */ +export async function dynamicImport(specifier: T): Promise { + return import(specifier); +}