unplugin-mtl
Version:
Import .mtl files as strings 🧵 in Vite, Rollup, Webpack + more
81 lines (74 loc) • 2.48 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/index.ts
var _unplugin = require('unplugin');
// src/utils/index.ts
var _sharp = require('sharp'); var _sharp2 = _interopRequireDefault(_sharp);
function loadImage(path2) {
return _sharp2.default.call(void 0, path2);
}
// src/utils/parseImport.ts
function parseURL(rawURL) {
return new URL(rawURL.replace(/#/g, "%23"), "file://");
}
// src/index.ts
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
var resourceRegex = / (.*\.(jpeg|jpg|mpc|mps|mpb|cxc|cxs|cxb|png|tga|webp|avif|tiff))/g;
var mtlRegex = /\.mtl\??/;
var src_default = _unplugin.createUnplugin.call(void 0, () => {
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(_path2.default.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}];
`;
}
exports.src_default = src_default;