Michael Lewis
Michael Lewis

Reputation: 4302

How does react avoid using require("../../Path/To/Module"), and just use require("Module")

As far as I've seen, npm modules can be require() without a path:

require("module") // --> npm module

and local modules are require() using a path:

require("./module") // --> local module, in this directory
require("../../path/to/module") // path to directory

In react.js, modules are required without a path. See here for example. I'm wondering how they achieve this.

Upvotes: 2

Views: 630

Answers (2)

Tomasz Racia
Tomasz Racia

Reputation: 1806

If you're using Webpack, you can add path/to/modules into resolve.modulesDirectories array and it will work similarly to requiring from node_modules instead of using relative paths.

resolve: { modulesDirectories: ['path/to/modules', 'node_modules'], },

and then

var foo = require('foo'); // Instead of: // var foo = require('/path/to/modules/foo'); // or // var foo = require('../../foo');

Upvotes: 1

fardjad
fardjad

Reputation: 20424

Apparently it uses rewrite-modules Babel plugin with module-map module (see gulpfile.js.)

There's also this Babel plugin that you can use to achieve the same behavior.

Upvotes: 3

Related Questions