reset-search-paths.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import * as path from 'path'
  2. const Module = require('module')
  3. // Clear Node's global search paths.
  4. Module.globalPaths.length = 0
  5. // Clear current and parent(init.js)'s search paths.
  6. module.paths = []
  7. module.parent!.paths = []
  8. // Prevent Node from adding paths outside this app to search paths.
  9. const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep
  10. const originalNodeModulePaths = Module._nodeModulePaths
  11. Module._nodeModulePaths = function (from: string) {
  12. const paths: string[] = originalNodeModulePaths(from)
  13. const fromPath = path.resolve(from) + path.sep
  14. // If "from" is outside the app then we do nothing.
  15. if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
  16. return paths.filter(function (candidate) {
  17. return candidate.startsWith(resourcesPathWithTrailingSlash)
  18. })
  19. } else {
  20. return paths
  21. }
  22. }
  23. const BASE_INTERNAL_PATH = path.resolve(__dirname, '..')
  24. const INTERNAL_MODULE_PREFIX = '@electron/internal/'
  25. // Patch Module._resolveFilename to always require the Electron API when
  26. // require('electron') is done.
  27. const electronPath = path.join(__dirname, '..', process.type!, 'api', 'exports', 'electron.js')
  28. const originalResolveFilename = Module._resolveFilename
  29. Module._resolveFilename = function (request: string, parent: NodeModule, isMain: boolean) {
  30. if (request === 'electron') {
  31. return electronPath
  32. } else if (request.startsWith(INTERNAL_MODULE_PREFIX) && request.length > INTERNAL_MODULE_PREFIX.length) {
  33. const slicedRequest = request.slice(INTERNAL_MODULE_PREFIX.length)
  34. return path.resolve(BASE_INTERNAL_PATH, `${slicedRequest}${slicedRequest.endsWith('.js') ? '' : '.js'}`)
  35. } else {
  36. return originalResolveFilename(request, parent, isMain)
  37. }
  38. }