Magic of babel register
I needed to do something like what it does at work. So to learn how it work I peeked into babel-register's source. It's very small. The the transpiling stuff is done by babel core so they were outside the source. I was after the stuff that does the require magic and within minutes I found what I was looking for.
Here is a way to extend require to text files.
This is cool! But..
Since the Module system is locked, this feature will probably never go away.But it also say,
I can see two reasons why this is bad.
- Require extensions is global.
The .ts extension handler set by this package could be over-written by another package that use TypeScript.
The second package could be using a compiler for a different version of TypeScript. Now that compiler will try to compile the first package's TypeScript sources and will break it!
- Compilation unnecessarily takes time
When an application developer install the package written in TypeScript he/she will be compiling it every time their app is run. But the packages source won't change. So they will be compiling the same source files over and over again.If the source is precompiled and published these problems does not occur.
Its not hard to understand that using require extensions this way should be avoided. But what about using it for development? Development is where we use babel-register. Development is where I needed it too.
So if we want a to run the front end code on node we have to run webpack on node. Tests are run often so should run fast. Running webpack and saving a file and then requiring it again takes time. It's common for a webpack build to take around 5 seconds. That is what we tried to avoid with require extensions.
We made a substitute for webpack loaders in a few lines using require extensions.
The loader function mimics some loader for the file extension ext.
For example following mimics the url loader for jpgs.
If we consider css content is not important for our tests, because say we only need to test if we add the correct css classes at correct places, we can ignore css with a loader function like following.