runtime-generator.js 2.0 KB

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