From 062a852a796b1c56e7e964bbbf2f5246da42f32a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20S=C3=A1nchez=20Jim=C3=A9nez?= Date: Sat, 26 Feb 2022 20:44:39 +0100 Subject: [PATCH] feat(next): split modern loader for node and browser support --- packages/utils/src/loader/loaders.ts | 42 +++++++++++++++------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/packages/utils/src/loader/loaders.ts b/packages/utils/src/loader/loaders.ts index da2a87c..fe2c3f8 100644 --- a/packages/utils/src/loader/loaders.ts +++ b/packages/utils/src/loader/loaders.ts @@ -2,6 +2,7 @@ import type { Awaitable } from '@antfu/utils'; import { promises as fs, Stats } from 'fs'; import type { CustomIconLoader } from './types'; import { camelize, pascalize } from '../misc/strings'; +import { isNode } from './loader'; /** * Returns CustomIconLoader for loading icons from a directory @@ -10,25 +11,26 @@ export function FileSystemIconLoader( dir: string, transform?: (svg: string) => Awaitable ): CustomIconLoader { - return async (name) => { - const paths = [ - `${dir}/${name}.svg`, - `${dir}/${camelize(name)}.svg`, - `${dir}/${pascalize(name)}.svg`, - ]; - let stat: Stats; - for (const path of paths) { - try { - stat = await fs.lstat(path); - } catch (err) { - continue; + return isNode + ? async (name) => { + const paths = [ + `${dir}/${name}.svg`, + `${dir}/${camelize(name)}.svg`, + `${dir}/${pascalize(name)}.svg`, + ]; + let stat: Stats; + for (const path of paths) { + try { + stat = await fs.lstat(path); + } catch (err) { + continue; + } + if (stat.isFile()) { + const svg = await fs.readFile(path, 'utf-8'); + return typeof transform === 'function' + ? await transform(svg) + : svg; + } } - if (stat.isFile()) { - const svg = await fs.readFile(path, 'utf-8'); - return typeof transform === 'function' - ? await transform(svg) - : svg; - } - } - }; + } : () => undefined; }