Nodejs - Quick Tips #3
07/03/2016, SunBabel - 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
require("babel-core/register")({
presets: ["es2015"],
});
This technique is more suited for activities which do not need quick processing time because this method really slows execution.
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 when 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 start the npm at the entry point.
// child_process
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
});