UNPKG

unplugin-mtl

Version:

Import .mtl files as strings 🧵 in Vite, Rollup, Webpack + more

81 lines (76 loc) • 2.16 kB
// src/index.ts import { createUnplugin } from "unplugin"; // src/utils/index.ts import sharp from "sharp"; function loadImage(path2) { return sharp(path2); } // src/utils/parseImport.ts function parseURL(rawURL) { return new URL(rawURL.replace(/#/g, "%23"), "file://"); } // src/index.ts import path from "path"; var resourceRegex = / (.*\.(jpeg|jpg|mpc|mps|mpb|cxc|cxs|cxb|png|tga|webp|avif|tiff))/g; var mtlRegex = /\.mtl\??/; var src_default = createUnplugin(() => { return { name: "unplugin-mtl", resolveId(id) { if (id.match(mtlRegex)) { return id; } }, async transform(src, id) { if (id.endsWith(".mtl")) { const contents = String.raw`${src}`; const code = await getCode(contents, id); if (code) { return { code, map: null }; } } } }; }); async function getCode(contents, id) { const matches = contents.match(resourceRegex); if (!matches) { return ` export const mtl = \`${contents}\` export const extRef = false; export const extRefHelpers = []; `; } const idURL = parseURL(id).pathname; const imports = []; const extRefData = []; const uniqueMatches = matches.filter((value, index, self) => self.indexOf(value) === index); const trimmedMatches = uniqueMatches.map((item) => item.trim()); let replacedContents = `\`${contents}\``; for (let i = 0; i < trimmedMatches.length; i++) { replacedContents = replacedContents.replace(new RegExp(trimmedMatches[i], "g"), "${asset" + i + "}"); imports.push(`import asset${i} from './${trimmedMatches[i]}';`); const image = await loadImage(path.dirname(idURL) + "/" + trimmedMatches[i]); const metadata = await image.metadata(); if (metadata) { const imgData = `{ src: asset${i}, width: ${metadata.width}, height: ${metadata.height}, }`; extRefData.push(imgData); } } return ` ${imports.join("\n")} export const mtl = ${replacedContents}; export const extRef = true; export const extRefHelpers = [${extRefData}]; `; } export { src_default };