cjs-shim.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
  3. function cjsShim() {
  4. let config;
  5. let isCjs;
  6. return {
  7. name: "vite-plugin-electron-renderer:cjs-shim",
  8. apply: "build",
  9. config(config2) {
  10. var _a, _b;
  11. config2.build ?? (config2.build = {});
  12. (_a = config2.build).cssCodeSplit ?? (_a.cssCodeSplit = false);
  13. (_b = config2.build).assetsDir ?? (_b.assetsDir = "");
  14. },
  15. configResolved(_config) {
  16. config = _config;
  17. const output = config.build.rollupOptions.output;
  18. if (output) {
  19. const formats = ["cjs", "commonjs"];
  20. if (Array.isArray(output) ? output.find((o) => formats.includes(o.format)) : formats.includes(output.format)) {
  21. isCjs = true;
  22. }
  23. }
  24. },
  25. transformIndexHtml(html) {
  26. if (!isCjs)
  27. return;
  28. const headRE = /(<\s*?head\s*?>)/;
  29. const assetsDir = config.build.assetsDir;
  30. if (assetsDir) {
  31. const requireIdShim = `<script id="shim-require-id">
  32. ; (function () {
  33. if (typeof require !== 'function') return;
  34. var Module = require('module');
  35. var _resolveFilename = Module._resolveFilename;
  36. Module._resolveFilename = function (request, parent, isMain, options) {
  37. // "assetsDir" is always at the same level as "index.html"
  38. var prefix = './';
  39. if (request.startsWith(prefix)) {
  40. try {
  41. // TODO: The way is more elegant.
  42. var newRequest = request.replace(prefix, prefix + '${assetsDir + "/"}');
  43. return _resolveFilename.call(this, newRequest, parent, isMain, options);
  44. } catch (error) { }
  45. }
  46. return _resolveFilename.call(this, request, parent, isMain, options);
  47. };
  48. })();
  49. <\/script>`;
  50. html = html.replace(headRE, "$1\n" + requireIdShim);
  51. }
  52. const exportsShim = `<script id="shim-exports">var exports = typeof module !== 'undefined' ? module.exports : {};<\/script>`;
  53. html = html.replace(headRE, "$1\n" + exportsShim);
  54. return html;
  55. }
  56. };
  57. }
  58. exports.default = cjsShim;