plugin.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. /**
  6. * @type {() => import('rollup').Plugin}
  7. */
  8. export function urlToEsmPlugin() {
  9. return {
  10. name: 'import-meta-url',
  11. async transform(code, id) {
  12. if (this.environment?.mode === 'dev') {
  13. return;
  14. }
  15. let idx = 0;
  16. // Look for `new URL("...?worker", import.meta.url)` patterns.
  17. const regex = /new\s+URL\s*\(\s*(['"`])(.*?)\?worker\1\s*,\s*import\.meta\.url\s*\)?/g;
  18. let match;
  19. let modified = false;
  20. let result = code;
  21. let offset = 0;
  22. /** @type {string[]} */
  23. const additionalImports = [];
  24. while ((match = regex.exec(code)) !== null) {
  25. let path = match[2];
  26. if (!path.startsWith('.') && !path.startsWith('/')) {
  27. path = `./${path}`;
  28. }
  29. const start = match.index;
  30. const end = start + match[0].length;
  31. const varName = `__worker_url_${idx++}__`;
  32. additionalImports.push(`import ${varName} from ${JSON.stringify(path + '?worker&url')};`);
  33. const replacement = varName;
  34. result = result.slice(0, start + offset) + replacement + result.slice(end + offset);
  35. offset += replacement.length - (end - start);
  36. modified = true;
  37. }
  38. if (!modified) {
  39. return null;
  40. }
  41. result = additionalImports.join('\n') + '\n' + result;
  42. return {
  43. code: result,
  44. map: null
  45. };
  46. }
  47. };
  48. }