UNPKG

vite-svg-vue-component

Version:

Use svg as vue components with support for both vue2.7 and vue3.x

86 lines (82 loc) 2.81 kB
var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); // src/index.ts import { readFileSync } from "fs"; import { createFilter } from "@rollup/pluginutils"; import { optimize } from "svgo"; // src/utils.ts import { basename } from "path"; import { getPackageInfoSync } from "local-pkg"; async function compileSvg(svg, path, options) { const version = options.vueVersion || detectVueVersion(); if (version === 2) { const { compileTemplate } = await import("compiler-sfc-v2"); const { code } = compileTemplate({ source: svg.replace("<svg", '<svg v-on="$listeners"'), filename: `${basename(path)}.vue`, transformAssetUrls: false }); return code; } else { const { compileTemplate } = await import("compiler-sfc-v3"); const { code } = compileTemplate({ id: path, source: svg, filename: `${basename(path)}.vue`, transformAssetUrls: false }); return code; } } function detectVueVersion(root = process.cwd()) { const vuePkg = getPackageInfoSync("vue", { paths: [root] }); if (vuePkg && vuePkg.version) return Number.parseInt(vuePkg.version); else return 3; } // src/index.ts var PLUGIN_NAME = "vite-svg-vue-component"; function createPlugin(options = {}) { const filter = createFilter( options.include || [/\.svg(\?component)?$/], options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/] ); return { name: PLUGIN_NAME, enforce: "pre", async transform(_code, id) { if (!filter(id)) return; const [path] = id.split("?", 2); let svg = readFileSync(path, { encoding: "utf-8" }); if (options.optimize) svg = optimize(svg, typeof options.optimize === "object" ? __spreadProps(__spreadValues({}, options.optimize), { path }) : { path }).data; const code = await compileSvg(svg, path, options); return `${code} export default { render };`; } }; } var src_default = createPlugin; export { PLUGIN_NAME, src_default as default };