reset-search-paths.ts 2.1 KB

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