runtime-generator.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const { stringifyRequest } = require('loader-utils');
  2. const {
  3. stringify,
  4. stringifySymbol,
  5. generateImport,
  6. generateExport,
  7. generateSpritePlaceholder
  8. } = require('./utils');
  9. /**
  10. * @param {Object} params
  11. * @param {SpriteSymbol} params.symbol - Sprite symbol instance {@see https://git.io/v9k8g}
  12. * @param {SVGSpriteLoaderConfig} params.config - Parsed loader config
  13. * @param {string} params.context - Context folder of current processing module
  14. * @param {Object} params.loaderContext {@see https://webpack.js.org/api/loaders/#the-loader-context}
  15. * @return {string}
  16. */
  17. function runtimeGenerator(params) {
  18. const { symbol, config, context } = params;
  19. const { extract, esModule, spriteModule, symbolModule, runtimeCompat } = config;
  20. let runtime;
  21. if (extract) {
  22. const spritePlaceholder = generateSpritePlaceholder(symbol.request.toString());
  23. runtime = generateExport(
  24. stringify(spritePlaceholder),
  25. esModule
  26. );
  27. } else {
  28. const spriteModuleImport = stringifyRequest({ context }, spriteModule);
  29. const symbolModuleImport = stringifyRequest({ context }, symbolModule);
  30. runtime = [
  31. generateImport('SpriteSymbol', symbolModuleImport, esModule),
  32. generateImport('sprite', spriteModuleImport, esModule),
  33. `var symbol = new SpriteSymbol(${stringifySymbol(symbol)})`,
  34. 'var result = sprite.add(symbol)',
  35. generateExport(runtimeCompat ? '"#" + result.id' : 'symbol', esModule)
  36. ].join(';\n');
  37. }
  38. return runtime;
  39. }
  40. module.exports = runtimeGenerator;