Nodejs - Quick Tips #6

Babel - Requiring ES2015 File from ES5

In the situation where you desire to use a ES5 file to refer to a ES2015 file, the on-the-fly compilation option of Babel can be one of the ways to do so.

This case might come up when you are intending to run an init file that you do not want to perform any Babel compilation, but you still want the ES5 file to serve as the entry point for your module.

On the Fly Compilation
presets: ['es2015']

This technique more suited for activities which do not need fast processing time because this method really slows execution down.

It will be more appropriate for operations that are not frequently run, such as some tests, and it would also not be advisable for initializing a cli node module because the slowdown will be quite evident.

As a side note for speeding up node cli execution, it is more beneficial to reduce the number of ‘require’ calls as noted here, which makes for the argument of using webpack to bundle your NPM modules into one file.

Testing Command Line NPM Modules

Most NPM modules are used programmatically through importing or requiring them into the file you are working on, but for the other times where your NPM module is used as a CLI module, input will need to be taken from the console.

For the properly testing of these CLI modules, the ‘childProcess.exec’ method can be used. The following example will starts the npm at the entry point

import childProcess from 'child_process';
const exec = childProcess.exec;

//Point to the entry point of NPM module
const cliEntryFile = 'node ' + __dirname + '/../bin/my-cli-init.js';

//Execute the command line with the supplied argument
exec(cliEntryFile + ' my-cool-command', function(error, stdout, stderr) {
//Rest of command actions

The above shows that node will execute the exact entry file (the ‘main’ key in package.json) with the command of your choice for your test cases.