Skip to content

Commit

Permalink
feat: add raster image support
Browse files Browse the repository at this point in the history
  • Loading branch information
meowtec authored and 朱勃 committed Jan 27, 2021
1 parent d216557 commit 16af42a
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 237 deletions.
19 changes: 16 additions & 3 deletions lib/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ const SVGCompiler = require('svg-baker');
const { NAMESPACE } = require('./config');
const configure = require('./configurator');
const Exceptions = require('./exceptions');
const fileTypeDetect = require('./utils/file-type-detect');

let svgCompiler = new SVGCompiler();

// eslint-disable-next-line consistent-return
module.exports = function loader(content) {
module.exports = function loader(contentBuffer) {
if (this.cacheable) {
this.cacheable();
}
Expand All @@ -24,7 +25,13 @@ module.exports = function loader(content) {
const parentCompiler = isChildCompiler ? compiler.parentCompilation.compiler : null;
const matchedRules = getOptions(loaderContext);

if (!content.includes('<svg')) {
const content = contentBuffer.toString();
const isSVG = fileTypeDetect.isSVG(content);

if (
!isSVG &&
!fileTypeDetect.isImage(contentBuffer)
) {
throw new Exceptions.InvalidSvg(content, matchedRules);
}

Expand Down Expand Up @@ -72,11 +79,17 @@ module.exports = function loader(content) {
regExp: config.symbolRegExp
});
}
svgCompiler.addSymbol({ id, content, path: resourcePath + resourceQuery })
svgCompiler.addSymbol({
id,
content: isSVG ? content : contentBuffer,
path: resourcePath + resourceQuery
})
.then((symbol) => {
const runtime = runtimeGenerator({ symbol, config, context: loaderContext.context, loaderContext });
done(null, runtime);
}).catch(done);
};

module.exports.NAMESPACE = NAMESPACE;

module.exports.raw = true;
27 changes: 27 additions & 0 deletions lib/utils/file-type-detect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const imageSize = require('image-size');

/**
* detect whether content is an image
* @param {Buffer} content
* @return {boolean}
*/
function isImage(content) {
try {
imageSize(content);
return true;
} catch (err) {
return false;
}
}

/**
* detect whether content is an image
* @param {string} content
* @return {boolean}
*/
function isSVG(content) {
return content.includes('<svg');
}

exports.isImage = isImage;
exports.isSVG = isSVG;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"deepmerge": "1.3.2",
"domready": "1.0.8",
"escape-string-regexp": "1.0.5",
"image-size": "^0.5.5",
"loader-utils": "^1.1.0",
"svg-baker": "^1.5.0",
"svg-baker-runtime": "^1.4.7",
Expand Down
Loading

0 comments on commit 16af42a

Please sign in to comment.