image-size-loader icon indicating copy to clipboard operation
image-size-loader copied to clipboard

Editing suggestion to work with quasar-framework

Open ianclever opened this issue 8 years ago • 0 comments

I fixed this bug to work with quasar-framework, if you want to generalize it for your own purposes here it is.

index:

var loaderUtils = require('loader-utils');
var sizeOf = require('image-size');
var fs = require('fs');

var imageToString = function(image) {
  if(image.src.match(/^data:[a-zA-Z0-9]+\/[a-zA-Z0-9]+;base64,/) === null){
	  image.src = '__webpack_public_path__ + ' + JSON.stringify(image.src);
  }else {
	  image.src = '"' + image.src + '"';
  }
  return 'module.exports = {' + '\n'
    + '  src: ' + image.src + ',\n'
    + '  width: ' + JSON.stringify(image.width) + ',\n'
    + '  height: ' + JSON.stringify(image.height) + ',\n'
    + '  bytes: ' + JSON.stringify(image.bytes) + ',\n'
    + '  type: ' + JSON.stringify(image.src) + ',\n'
    + '};' + '\n'

    // For requires from CSS when used with webpack css-loader,
    // outputting an Object doesn't make sense,
    // So overriding the toString method to output just the URL
    + 'module.exports.toString = function() {' + '\n'
    + '  return ' + image.src + ';\n'
    + '};';
};

module.exports = function(content) {
  this.cacheable && this.cacheable(true);
  if(!this.emitFile) throw new Error('emitFile is required from module system');
  this.addDependency(this.resourcePath);

  var query = loaderUtils.parseQuery(this.query);
  var filename = "[name].[ext]";

  if ('string' === typeof query.name) {
    filename = query.name;
  }	

  /* correction */
  var str = content.toString();
  str = str.replace(/^module\.exports =( __webpack_public_path__ \+)? \"/, '');
  str = str.replace(/\";?$/, '');
  var url = str;
  if(str.match(/^data:[a-zA-Z0-9]+\/[a-zA-Z0-9]+;base64,/) !== null){
	content = Buffer.from(str.replace(/^data:[a-zA-Z0-9]+\/[a-zA-Z0-9]+;base64,/, ''), 'base64');
  }else if(str.match(/^img\//) !== null){
	var arr = str.split('.'); 
	content = new Buffer(arr[0]+ '.' + arr[2]);
  }else {
	var url = loaderUtils.interpolateName(this, filename, {
	  context: query.context || this.options.context,
      content: content,
      regExp: query.regExp
	});
  }
  /* correction */

  var image = sizeOf(this.resourcePath);

  image.src = url;
  image.bytes = fs.statSync(this.resourcePath).size;

  return imageToString(image);

};

module.exports.raw = true;

note: svg reading did not work correctly with me.

ianclever avatar Dec 22 '17 19:12 ianclever