unplugin-iconify
Version:
Unplugin for iconify.
265 lines (252 loc) • 8.73 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/nuxt.ts
var nuxt_exports = {};
__export(nuxt_exports, {
default: () => nuxt_default
});
module.exports = __toCommonJS(nuxt_exports);
var import_kit = require("@nuxt/kit");
// src/vite.ts
var import_unplugin2 = require("unplugin");
// src/index.ts
var import_pathe2 = __toESM(require("pathe"), 1);
var import_unplugin = require("unplugin");
// src/core/helpers/generate.ts
var import_crypto = __toESM(require("crypto"), 1);
var import_utils = require("@iconify/utils");
var import_fs_extra = __toESM(require("fs-extra"), 1);
var import_pathe = __toESM(require("pathe"), 1);
var import_tools = require("@iconify/tools");
// src/core/log.ts
var import_consola = __toESM(require("consola"), 1);
// src/core/constants.ts
var PLUGIN_ABBR = "ui";
var PLUGIN_CSS_PREFIX = `unplugin-iconify-css/`;
var IS_DEV = process.env.NODE_ENV === "development";
// src/core/log.ts
var logger = import_consola.default.withTag(PLUGIN_ABBR).withDefaults({
level: 3
});
// src/core/helpers/loader.ts
var import_node_fs = require("fs");
function locateIconSet(prefix) {
try {
const main = require.resolve(`@iconify-json/${prefix}/icons.json`);
const info = require.resolve(`@iconify-json/${prefix}/info.json`);
return {
main,
info
};
} catch (e) {
}
try {
const main = require.resolve(`@iconify/json/json/${prefix}.json`);
return {
main
};
} catch (e) {
}
}
var cache = /* @__PURE__ */ Object.create(null);
function loadIconSet(prefix, options) {
var _a;
let filename;
const customIconSet = (_a = options.iconSets) == null ? void 0 : _a[prefix];
if (customIconSet) {
switch (typeof customIconSet) {
case "function": {
const result = customIconSet();
if (options.iconSets) {
options.iconSets[prefix] = result;
}
return result;
}
case "string": {
filename = {
main: customIconSet
};
break;
}
default:
return customIconSet;
}
} else {
filename = locateIconSet(prefix);
}
if (!filename) {
return;
}
const main = typeof filename === "string" ? filename : filename.main;
if (cache[main]) {
return cache[main];
}
try {
const result = JSON.parse((0, import_node_fs.readFileSync)(main, "utf8"));
if (!result.info && typeof filename === "object" && filename.info) {
result.info = JSON.parse((0, import_node_fs.readFileSync)(filename.info, "utf8"));
}
cache[main] = result;
return result;
} catch (e) {
}
}
function ensureLoadIconSet(prefix, options) {
const iconSet = loadIconSet(prefix, options);
if (!iconSet) {
throw new Error(
`Cannot load icon set for "${prefix}". Install "@iconify-json/${prefix}" as dev dependency?`
);
}
return iconSet;
}
// src/core/helpers/generate.ts
async function generateIconSetsCss(cssGenerator, options) {
const { iconSets = {}, exportIcons, iconSelector, outputPath } = cssGenerator;
const { onCssHashGenerated } = options || {};
let cssCode = "";
if (exportIcons) {
if (Array.isArray(exportIcons)) {
exportIcons.forEach((prefix) => {
const iconSetJson = ensureLoadIconSet(prefix, { iconSets });
const iconSet = new import_tools.IconSet(iconSetJson);
iconSet.list(["icon", "variation", "alias"]).forEach((item) => {
const targetIconifyIcon = (0, import_utils.getIconData)(iconSetJson, item);
if (!targetIconifyIcon) {
return;
}
cssCode += (0, import_utils.getIconCSS)(targetIconifyIcon, {
iconSelector: iconSelector == null ? void 0 : iconSelector.replace("{prefix}", iconSet.prefix).replace("{name}", item)
});
});
});
} else {
Object.keys(exportIcons).forEach((prefix) => {
const iconSetJson = ensureLoadIconSet(prefix, {
iconSets
});
const iconSet = new import_tools.IconSet(iconSetJson);
const iconNames = exportIcons[prefix];
const exportIconNames = iconNames instanceof RegExp ? iconSet.list(["icon", "variation", "alias"]).filter((item) => {
return iconNames.test(item);
}) : iconNames;
exportIconNames.forEach((item) => {
const targetIconifyIcon = (0, import_utils.getIconData)(iconSetJson, item);
if (!targetIconifyIcon) {
return;
}
cssCode += (0, import_utils.getIconCSS)(targetIconifyIcon, {
iconSelector: iconSelector == null ? void 0 : iconSelector.replace("{prefix}", iconSet.prefix).replace("{name}", item)
});
});
});
}
}
const getCssHash = () => {
const cssHash = import_crypto.default.createHash("md5").update(cssCode.replace(/[ \n\t]/g, ""), "utf8").digest("hex").slice(0, 8);
onCssHashGenerated == null ? void 0 : onCssHashGenerated(cssHash);
logger.debug("generateIconSetsCss cssHash", cssHash);
return cssHash;
};
const normalizedPath = import_pathe.default.normalize(
typeof outputPath === "string" ? outputPath : outputPath(getCssHash())
);
await import_fs_extra.default.ensureDir(import_pathe.default.dirname(normalizedPath));
logger.debug("css output path", normalizedPath);
await import_fs_extra.default.writeFile(normalizedPath, cssCode, "utf-8");
}
// src/index.ts
var unpluginFactory = (options) => {
const { debug } = options || {};
const cssHashes = {};
if (debug) {
logger.level = 4;
}
return {
name: "unplugin-iconify",
buildStart: async () => {
const { cssGenerators = [] } = options || {};
await Promise.all(
cssGenerators.map((cssGenerator) => {
return generateIconSetsCss(cssGenerator, {
onCssHashGenerated: (cssHash) => {
if (cssGenerator.id) {
cssHashes[cssGenerator.id] = cssHash;
}
}
});
})
);
},
resolveId(id) {
if (id.startsWith(PLUGIN_CSS_PREFIX)) {
logger.debug("Got resolveId", id);
return id;
}
},
loadInclude(id) {
return id.startsWith(PLUGIN_CSS_PREFIX);
},
async load(id) {
const normalizeId = import_pathe2.default.normalize(id);
const cssGeneratorKey = id.replace(PLUGIN_CSS_PREFIX, "");
const cssHash = cssHashes[cssGeneratorKey];
logger.debug("Got load id", normalizeId);
logger.debug("cssGeneratorKey", cssGeneratorKey, "cssHash", cssHash);
return {
code: `
// import { cssHash } from 'unplugin-iconify-css/<key>'
export const cssHash = '${cssHash}'
`,
map: null
};
}
};
};
// src/vite.ts
var vite_default = (0, import_unplugin2.createVitePlugin)(unpluginFactory);
// src/webpack.ts
var import_unplugin3 = require("unplugin");
var webpack_default = (0, import_unplugin3.createWebpackPlugin)(unpluginFactory);
// src/nuxt.ts
var import_schema = require("@nuxt/schema");
var nuxt_default = (0, import_kit.defineNuxtModule)({
meta: {
name: "nuxt-unplugin-iconify",
configKey: "unpluginStarter"
},
defaults: {
// ...default options
},
setup(options, nuxt) {
(0, import_kit.addVitePlugin)(() => vite_default(options));
(0, import_kit.addWebpackPlugin)(() => webpack_default(options));
}
});
exports.default = module.exports;