reset-search-paths.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import * as path from 'path';
  2. const Module = require('module');
  3. // Clear Node's global search paths.
  4. Module.globalPaths.length = 0;
  5. // Prevent Node from adding paths outside this app to search paths.
  6. const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep;
  7. const originalNodeModulePaths = Module._nodeModulePaths;
  8. Module._nodeModulePaths = function (from: string) {
  9. const paths: string[] = originalNodeModulePaths(from);
  10. const fromPath = path.resolve(from) + path.sep;
  11. // If "from" is outside the app then we do nothing.
  12. if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
  13. return paths.filter(function (candidate) {
  14. return candidate.startsWith(resourcesPathWithTrailingSlash);
  15. });
  16. } else {
  17. return paths;
  18. }
  19. };
  20. // Make a fake Electron module that we will insert into the module cache
  21. const makeElectronModule = (name: string) => {
  22. const electronModule = new Module('electron', null);
  23. electronModule.id = 'electron';
  24. electronModule.loaded = true;
  25. electronModule.filename = name;
  26. Object.defineProperty(electronModule, 'exports', {
  27. get: () => require('electron')
  28. });
  29. Module._cache[name] = electronModule;
  30. };
  31. makeElectronModule('electron');
  32. makeElectronModule('electron/common');
  33. if (process.type === 'browser') {
  34. makeElectronModule('electron/main');
  35. }
  36. if (process.type === 'renderer') {
  37. makeElectronModule('electron/renderer');
  38. }
  39. const originalResolveFilename = Module._resolveFilename;
  40. Module._resolveFilename = function (request: string, parent: NodeModule, isMain: boolean, options?: { paths: Array<string>}) {
  41. if (request === 'electron' || request.startsWith('electron/')) {
  42. return 'electron';
  43. } else {
  44. return originalResolveFilename(request, parent, isMain, options);
  45. }
  46. };