From c8dd82b987785305cd9fd8439ce369d1a5038812 Mon Sep 17 00:00:00 2001 From: EGOIST Date: Thu, 16 Feb 2023 22:36:50 +0800 Subject: [PATCH] fix: allow to install icon packages individually --- src/core.ts | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/src/core.ts b/src/core.ts index 74d1690..06154ef 100644 --- a/src/core.ts +++ b/src/core.ts @@ -2,10 +2,17 @@ import path from "path" import fs from "fs" import { IconifyJSON } from "@iconify/types" import { getIconCSS, getIconData } from "@iconify/utils" +import { createRequire } from "module" import { CollectionNames } from "../types" +declare const TSUP_FORMAT: "esm" | "cjs" +const req = + typeof TSUP_FORMAT === "undefined" || TSUP_FORMAT === "cjs" + ? require + : createRequire(import.meta.url) + const localResolve = (cwd: string, id: string) => { - const resolved = require.resolve(id, { paths: [cwd] }) + const resolved = req.resolve(id, { paths: [cwd] }) return resolved } @@ -13,7 +20,26 @@ export const getIconCollections = ( include: CollectionNames[] | "all" = "all", ) => { const pkgPath = localResolve(process.cwd(), "@iconify/json/package.json") - if (!pkgPath) return {} + if (!pkgPath) { + if (Array.isArray(include)) { + return include.reduce((result, name) => { + const jsonPath = localResolve( + process.cwd(), + `@iconify-json/${name}/icons.json`, + ) + if (!jsonPath) { + throw new Error( + `Icon collection "${name}" not found. Please install @iconify-json/${name} or @iconify/json`, + ) + } + return { + ...result, + [name]: req(jsonPath), + } + }, {}) + } + return {} + } const pkgDir = path.dirname(pkgPath) const files = fs.readdirSync(path.join(pkgDir, "json")) const collections: Record = {} @@ -22,7 +48,7 @@ export const getIconCollections = ( include === "all" || include.includes(file.replace(".json", "") as any) ) { - const json: IconifyJSON = require(path.join(pkgDir, "json", file)) + const json: IconifyJSON = req(path.join(pkgDir, "json", file)) collections[json.prefix] = json } }