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