0

(This came up in https://github.com/daurnimator/lua.vm.js/issues/57#issuecomment-235377158)

In node.js, some functions/objects are not true globals, but 'local to each module', e.g. from https://nodejs.org/api/all.html#globals_require

require isn't actually a global but rather local to each module.

global.require seems to work in the node.js REPL:

$ node
> require
{ [Function: require]
  resolve: [Function: resolve],
  main: undefined,
  extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
  cache: {} }
> global.require
{ [Function: require]
  resolve: [Function: resolve],
  main: undefined,
  extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
  cache: {} }

But it doesn't work in a file.

How are require, module, exports, etc. implemented?

Is there a way to reliably access require given global?

daurnimator
  • 4,091
  • 18
  • 34
  • 1
    I don't think this is a duplicate. The OP is asking how to require builtins without having access to local scope variables like `require`, but having access to the global scope. – Tim Caswell Jul 26 '16 at 20:38
  • 1
    So digging through the internal module code in node, it seems that all builtin modules are exposed via magic hidden properties on the global object itself. https://github.com/nodejs/node/blob/e22ffefff221caee264ab0b88691478a03ab1862/lib/internal/module.js#L54-L96 – Tim Caswell Jul 26 '16 at 20:40

1 Answers1

0

You could add something like this in your main file.

global.lodash = require('lodash');

This will make lodash available in the global scope (in all your modules). But it's not really recommended to clutter the global scope.

Andrei Demian
  • 63
  • 1
  • 6