reset-search-paths.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import * as path from 'path';
  2. const Module = require('module');
  3. // Clear Node's global search paths.
  4. Module.globalPaths.length = 0;
  5. // We do not want to allow use of the VM module in the renderer process as
  6. // it conflicts with Blink's V8::Context internal logic.
  7. if (process.type === 'renderer') {
  8. const _load = Module._load;
  9. Module._load = function (request: string) {
  10. if (request === 'vm') {
  11. console.warn('The vm module of Node.js is deprecated in the renderer process and will be removed.');
  12. }
  13. return _load.apply(this, arguments);
  14. };
  15. }
  16. // Prevent Node from adding paths outside this app to search paths.
  17. const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep;
  18. const originalNodeModulePaths = Module._nodeModulePaths;
  19. Module._nodeModulePaths = function (from: string) {
  20. const paths: string[] = originalNodeModulePaths(from);
  21. const fromPath = path.resolve(from) + path.sep;
  22. // If "from" is outside the app then we do nothing.
  23. if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
  24. return paths.filter(function (candidate) {
  25. return candidate.startsWith(resourcesPathWithTrailingSlash);
  26. });
  27. } else {
  28. return paths;
  29. }
  30. };
  31. // Make a fake Electron module that we will insert into the module cache
  32. const makeElectronModule = (name: string) => {
  33. const electronModule = new Module('electron', null);
  34. electronModule.id = 'electron';
  35. electronModule.loaded = true;
  36. electronModule.filename = name;
  37. Object.defineProperty(electronModule, 'exports', {
  38. get: () => require('electron')
  39. });
  40. Module._cache[name] = electronModule;
  41. };
  42. makeElectronModule('electron');
  43. makeElectronModule('electron/common');
  44. if (process.type === 'browser') {
  45. makeElectronModule('electron/main');
  46. }
  47. if (process.type === 'renderer') {
  48. makeElectronModule('electron/renderer');
  49. }
  50. const originalResolveFilename = Module._resolveFilename;
  51. Module._resolveFilename = function (request: string, parent: NodeModule, isMain: boolean, options?: { paths: Array<string>}) {
  52. if (request === 'electron' || request.startsWith('electron/')) {
  53. return 'electron';
  54. } else {
  55. return originalResolveFilename(request, parent, isMain, options);
  56. }
  57. };