index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.default = void 0;
  4. var _loaderUtils = require("loader-utils");
  5. var _core = require("@babel/core");
  6. var _core2 = _interopRequireDefault(require("@svgr/core"));
  7. var _pluginSvgo = _interopRequireDefault(require("@svgr/plugin-svgo"));
  8. var _pluginJsx = _interopRequireDefault(require("@svgr/plugin-jsx"));
  9. var _presetReact = _interopRequireDefault(require("@babel/preset-react"));
  10. var _presetEnv = _interopRequireDefault(require("@babel/preset-env"));
  11. var _pluginTransformReactConstantElements = _interopRequireDefault(require("@babel/plugin-transform-react-constant-elements"));
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. const babelOptions = {
  14. babelrc: false,
  15. configFile: false,
  16. presets: [(0, _core.createConfigItem)(_presetReact.default, {
  17. type: 'preset'
  18. }), (0, _core.createConfigItem)([_presetEnv.default, {
  19. modules: false
  20. }], {
  21. type: 'preset'
  22. })],
  23. plugins: [(0, _core.createConfigItem)(_pluginTransformReactConstantElements.default)]
  24. };
  25. function svgrLoader(source) {
  26. const callback = this.async();
  27. const {
  28. babel = true,
  29. ...options
  30. } = (0, _loaderUtils.getOptions)(this) || {};
  31. const readSvg = () => new Promise((resolve, reject) => {
  32. this.fs.readFile(this.resourcePath, (err, result) => {
  33. if (err) reject(err);
  34. resolve(result);
  35. });
  36. });
  37. const previousExport = (() => {
  38. if (source.toString('utf-8').startsWith('export ')) {
  39. return source;
  40. }
  41. const exportMatches = source.toString('utf-8').match(/^module.exports\s*=\s*(.*)/);
  42. return exportMatches ? `export default ${exportMatches[1]}` : null;
  43. })();
  44. const tranformSvg = svg => (0, _core2.default)(svg, options, {
  45. caller: {
  46. name: '@svgr/webpack',
  47. previousExport,
  48. defaultPlugins: [_pluginSvgo.default, _pluginJsx.default]
  49. },
  50. filePath: this.resourcePath
  51. }).then(jsCode => {
  52. if (!babel) return jsCode;
  53. return (0, _core.transformAsync)(jsCode, babelOptions).then(({
  54. code
  55. }) => code);
  56. }).then(result => callback(null, result)).catch(err => callback(err));
  57. if (previousExport) {
  58. readSvg().then(tranformSvg);
  59. } else {
  60. tranformSvg(source);
  61. }
  62. }
  63. var _default = svgrLoader;
  64. exports.default = _default;