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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With