utils.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. function arrayClear(array) {
  2. return array.filter(function (v) { return !!v });
  3. }
  4. /**
  5. * Return the import path/name of an UMD module for the given module format.
  6. *
  7. * @param {string} name - name of the module, used if no other no import path/name can be found.
  8. * @param {object|string} config - external configuration.
  9. * - If a string, returns it (we consider this is the path or name).
  10. * - If an object, returns the property within it according to the given `format`,
  11. * or the "default" property.
  12. * @param {string} format - format of the module to look for, if the configuration is an object.
  13. *
  14. * @return The found import path/name for the module.
  15. */
  16. function getUmdEntry(name, config, format) {
  17. if (typeof config === 'string') {
  18. return config;
  19. }
  20. if (typeof config === 'object') {
  21. if (config[format] != null) return config[format];
  22. if (config.default != null) return config.default;
  23. }
  24. return name;
  25. }
  26. /**
  27. * Generate an configuration object for Webpack Externals for UMD modules.
  28. * See: https://webpack.js.org/configuration/externals/#object
  29. *
  30. * @param {object} externals - Configuration object for external UMD modules.
  31. * For each entry, a string or an object can be provided.
  32. * - If a string, it is used for all module formats.
  33. * - If an object, it is used as is and the "default" property or the module
  34. * name is used for missing formats.
  35. * @param {object} {} options- Additional options:
  36. * - namespace {string} '' - Global variable in which the modules must be
  37. * searched in instead of the root for module-less environments.
  38. *
  39. * @return {object} Generated configuration for Webpack Externals
  40. */
  41. module.exports.umdExternals = function(externals, options) {
  42. options = Object.assign({ namespace: '' }, options);
  43. var config = {};
  44. Object.keys(externals).forEach(function (name) {
  45. var entryConfig = externals[name];
  46. config[name] = {
  47. root: arrayClear([ options.namespace, getUmdEntry(name, entryConfig, 'root') ]),
  48. amd: getUmdEntry(name, entryConfig, 'amd'),
  49. commonjs: getUmdEntry(name, entryConfig, 'commonjs'),
  50. commonjs2: getUmdEntry(name, entryConfig, 'commonjs2'),
  51. };
  52. }, {});
  53. return config;
  54. };