runtime-generator.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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, publicPath } = config;
  20. let runtime;
  21. if (extract) {
  22. const spritePlaceholder = generateSpritePlaceholder(symbol.request.file);
  23. const path = stringify(publicPath) || '__webpack_public_path__';
  24. const data = `{
  25. id: ${stringify(symbol.useId)},
  26. viewBox: ${stringify(symbol.viewBox)},
  27. url: ${path} + ${stringify(spritePlaceholder)},
  28. toString: function () {
  29. return this.url;
  30. }
  31. }`;
  32. runtime = generateExport(data, esModule);
  33. } else {
  34. const spriteModuleImport = stringifyRequest({ context }, spriteModule);
  35. const symbolModuleImport = stringifyRequest({ context }, symbolModule);
  36. runtime = [
  37. generateImport('SpriteSymbol', symbolModuleImport, esModule),
  38. generateImport('sprite', spriteModuleImport, esModule),
  39. `var symbol = new SpriteSymbol(${stringifySymbol(symbol)})`,
  40. 'var result = sprite.add(symbol)',
  41. generateExport(runtimeCompat ? '"#" + symbol.id' : 'symbol', esModule)
  42. ].join(';\n');
  43. }
  44. return runtime;
  45. }
  46. module.exports = runtimeGenerator;