Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the React library require its source libraries directly?

I was looking through the source code of Facebook's React and saw that throughout the source of the project they don't specify relative paths for loading its own modules. For example, instead of doing var foo = require('../bar/foobar') the library uses var foo = require('foobar') as if the module was loaded in node_modules already for CommonJS to read.

I was just wondering how they managed to do this? I tried looking through their build steps through Grunt but couldn't see any packages that directly accomplish this.

For a more concrete example of the technique I"m talking about, here the library calls the flattenChildren module which exists in a different directory altogether without specifying the path.

like image 921
Josh Black Avatar asked Feb 21 '15 09:02

Josh Black


1 Answers

React uses a tool called commoner. Their configuration of it matches up the lines that look like this:

* @providesModule ReactChildReconciler

To require('ReactChildReconciler') calls. They also put everything in a single directory, so the paths end up as require('./ReactChildReconciler').

The source code is organized in a structured way, but the module names are globally unique to the repo (and all of facebook's internal code, I think [citation needed]). This means there's no ambiguity in what it points to.


On the subject, there are also some other magical things in react's code.

The calls to invariant(assertion, explanation, ...) and the similar warning calls are transformed for the production build by removing the arguments after the first one to save space. Warning calls are stripped entirely, because they're wrapped in the next piece of magic: development only blocks.

if (__DEV__) {
   ...
}

Which compiles to:

if (process.env.NODE_ENV !== 'production') {
   ...
}

Which, via envify, compiles to this (in development), and the code runs:

if ('development' !== 'production') {
   ...
}

And this in production:

if ('production' !== 'production') {
   ...
}

Which minifies to this:

like image 95
Brigand Avatar answered Oct 19 '22 23:10

Brigand