index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const MagicString = require("magic-string");
  2. const {createFilter} = require("@rollup/pluginutils");
  3. const importToGlobals = require("./lib/import-to-globals");
  4. const defaultDynamicWrapper = id => `Promise.resolve(${id})`;
  5. function createPlugin(globals, {include, exclude, dynamicWrapper = defaultDynamicWrapper} = {}) {
  6. if (!globals) {
  7. throw new TypeError("Missing mandatory option 'globals'");
  8. }
  9. let getName = globals;
  10. const globalsType = typeof globals;
  11. const isGlobalsObj = globalsType === "object";
  12. if (isGlobalsObj) {
  13. getName = function (name) {
  14. if (Object.prototype.hasOwnProperty.call(globals, name)) {
  15. return globals[name];
  16. }
  17. };
  18. } else if (globalsType !== "function") {
  19. throw new TypeError(`Unexpected type of 'globals', got '${globalsType}'`);
  20. }
  21. const dynamicWrapperType = typeof dynamicWrapper;
  22. if (dynamicWrapperType !== "function") {
  23. throw new TypeError(`Unexpected type of 'dynamicWrapper', got '${dynamicWrapperType}'`);
  24. }
  25. const filter = createFilter(include, exclude);
  26. return {
  27. name: "rollup-plugin-external-globals",
  28. transform
  29. };
  30. function transform(code, id) {
  31. if ((id[0] !== "\0" && !filter(id)) || (isGlobalsObj && Object.keys(globals).every(id => !code.includes(id)))) {
  32. return;
  33. }
  34. const ast = this.parse(code);
  35. code = new MagicString(code);
  36. const isTouched = importToGlobals({
  37. ast,
  38. code,
  39. getName,
  40. getDynamicWrapper: dynamicWrapper
  41. });
  42. return isTouched ? {
  43. code: code.toString(),
  44. map: code.generateMap()
  45. } : undefined;
  46. }
  47. }
  48. module.exports = createPlugin;