node.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { isBrowserBundle } from './env.js';
  2. /**
  3. * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,
  4. * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.
  5. */
  6. /**
  7. * Checks whether we're in the Node.js or Browser environment
  8. *
  9. * @returns Answer to given question
  10. */
  11. function isNodeEnv() {
  12. // explicitly check for browser bundles as those can be optimized statically
  13. // by terser/rollup.
  14. return (
  15. !isBrowserBundle() &&
  16. Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'
  17. );
  18. }
  19. /**
  20. * Requires a module which is protected against bundler minification.
  21. *
  22. * @param request The module path to resolve
  23. */
  24. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
  25. function dynamicRequire(mod, request) {
  26. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  27. return mod.require(request);
  28. }
  29. /**
  30. * Helper for dynamically loading module that should work with linked dependencies.
  31. * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`
  32. * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during
  33. * build time. `require.resolve` is also not available in any other way, so we cannot create,
  34. * a fake helper like we do with `dynamicRequire`.
  35. *
  36. * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.
  37. * That is to mimic the behavior of `require.resolve` exactly.
  38. *
  39. * @param moduleName module name to require
  40. * @returns possibly required module
  41. */
  42. function loadModule(moduleName) {
  43. let mod;
  44. try {
  45. mod = dynamicRequire(module, moduleName);
  46. } catch (e) {
  47. // no-empty
  48. }
  49. try {
  50. const { cwd } = dynamicRequire(module, 'process');
  51. mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ;
  52. } catch (e) {
  53. // no-empty
  54. }
  55. return mod;
  56. }
  57. export { dynamicRequire, isNodeEnv, loadModule };
  58. //# sourceMappingURL=node.js.map