stencil-inline-svg
Version:
A Stenciljs plugin to insert inline SVGs into components
50 lines (45 loc) • 1.47 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Copied and adapted from @stencil/sass
* https://github.com/ionic-team/stencil-sass
*/
function usePlugin(fileName) {
return /\.svg$/i.test(fileName);
}
/**
* If the sourceText is a base64 string returned by
* rollup imagePlugin, remove the export part of the
* string and decode the base64 value
*
* @param sourceText - a rollup imagePlugin export string in the format const img = 'data:image/svg+xml;base64,...'; export default img;
*/
function decodeBase64SourceText(sourceText) {
let [, base64Code] = sourceText.split('base64,');
if (!base64Code) {
return false;
}
base64Code = base64Code.slice(0, base64Code.indexOf(`';`));
return Buffer.from(base64Code, 'base64').toString();
}
function inlineSvg() {
return {
name: 'inlineSvg',
transform(sourceText, fileName) {
if (!usePlugin(fileName)) {
return null;
}
if (sourceText === '') {
throw new Error('/** inlineSvg error: the SVG file is empty **/');
}
return new Promise(resolve => {
const svgCode = decodeBase64SourceText(sourceText) || sourceText;
resolve({
id: fileName,
code: `export default \`${svgCode}\``,
});
});
},
};
}
exports.inlineSvg = inlineSvg;