index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = loader;
  6. exports.raw = void 0;
  7. var _path = _interopRequireDefault(require("path"));
  8. var _loaderUtils = require("loader-utils");
  9. var _schemaUtils = _interopRequireDefault(require("schema-utils"));
  10. var _mimeTypes = _interopRequireDefault(require("mime-types"));
  11. var _normalizeFallback = _interopRequireDefault(require("./utils/normalizeFallback"));
  12. var _options = _interopRequireDefault(require("./options.json"));
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. function shouldTransform(limit, size) {
  15. if (typeof limit === 'boolean') {
  16. return limit;
  17. }
  18. if (typeof limit === 'string') {
  19. return size <= parseInt(limit, 10);
  20. }
  21. if (typeof limit === 'number') {
  22. return size <= limit;
  23. }
  24. return true;
  25. }
  26. function loader(src) {
  27. // Loader Options
  28. const options = (0, _loaderUtils.getOptions)(this) || {};
  29. (0, _schemaUtils.default)(_options.default, options, {
  30. name: 'URL Loader',
  31. baseDataPath: 'options'
  32. }); // No limit or within the specified limit
  33. if (shouldTransform(options.limit, src.length)) {
  34. const file = this.resourcePath;
  35. const mimetype = options.mimetype || _mimeTypes.default.contentType(_path.default.extname(file));
  36. if (typeof src === 'string') {
  37. // eslint-disable-next-line no-param-reassign
  38. src = Buffer.from(src);
  39. }
  40. const esModule = typeof options.esModule !== 'undefined' ? options.esModule : true;
  41. return `${esModule ? 'export default' : 'module.exports ='} ${JSON.stringify(`data:${mimetype || ''};base64,${src.toString('base64')}`)}`;
  42. } // Normalize the fallback.
  43. const {
  44. loader: fallbackLoader,
  45. options: fallbackOptions
  46. } = (0, _normalizeFallback.default)(options.fallback, options); // Require the fallback.
  47. // eslint-disable-next-line global-require, import/no-dynamic-require
  48. const fallback = require(fallbackLoader); // Call the fallback, passing a copy of the loader context. The copy has the query replaced. This way, the fallback
  49. // loader receives the query which was intended for it instead of the query which was intended for url-loader.
  50. const fallbackLoaderContext = Object.assign({}, this, {
  51. query: fallbackOptions
  52. });
  53. return fallback.call(fallbackLoaderContext, src);
  54. } // Loader Mode
  55. const raw = true;
  56. exports.raw = raw;