How to do it…

With Node modules, there are two important changes in how we export and import elements. Any file can be a module, as with ES modules. In a nutshell, in order to import something from a module, you'll have to use a require() function, and the module itself will use an exports object to specify what it will export.

JS math operators (addition, subtraction, and so on) don't do rounding, so let's write a roundmath.js module that will perform arithmetic, but rounding to cents, for an imagined business-related application. First, we get started with the common two lines that enable Flow, and set strict mode:

// Source file: src/roundmath.js

/* @flow */
"use strict";

// continues...
Don't forget to add the "use strict" line in all your modules, before the rest of your code, as we mentioned in the Working in strict mode section in the previous chapter. JS modules are strict by definition, but that doesn't apply to Node modules, which are not strict.

Then, let's define our functions. Just for variety, we'll have a couple of internal (not exported) functions, and several ones that will be exported:

// ...continued

// These won't be exported:

const roundToCents = (x: number): number => Math.round(x * 100) / 100;
const changeSign = (x: number): number => -x;

// The following will be exported:

const addR = (x: number, y: number): number => roundToCents(x + y);

const subR = (x: number, y: number): number => addR(x, changeSign(y));

const multR = (x: number, y: number): number => roundToCents(x * y);

const divR = (x: number, y: number): number => {
if (y === 0) {
throw new Error("Divisor must be nonzero");
} else {
return roundToCents(x / y);
}
};

// continues...

Finally, as per usual conventions, all exports will be together, at the bottom, so it will be easy to see everything that a module exports. Instead of the modern export statement, you assign whatever you want to export, to an exports object. If you want to keep variables or functions private, all you need do is skip assigning them; in our case, we are only exporting four of the six functions we coded:

// ...continued

exports.
addR = addR;
exports.subR = subR;
exports.multR = multR;
exports.divR = divR;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset