I'm just getting into using es 6 modules for front end development (we don't use Node at all), and am wondering if this pattern we've come up has any pitfalls or if you have any improvement suggestions. I guess it uses some of the rationale behind the revealing module pattern, in es6 modules. I ask this question because most es6 module "how to guides" I've seen do something different, which I'll note at the very bottom of the question.
Some things to note:
- We (are pretty sure we) want each module to only export one thing. This is listed as a best practice in the Airbnb style guide, and we've just found it nice overall when consuming npm packages
- We really like naming methods with "public" and "private" (guess we should be using _ for private methods as that's newer best-practice), it makes it easy to see what is available outside of the module
module.js:
// publicly available method
function publicHello() {
return 'Hello';
};
// publicly available method
function publicHelloWorld(){
const a = publicHello();
const b = privateProcessWorld(a);
return b;
};
// private method
function privateProcessWorld(x) {
return x + ' world';
};
// create an object to export, containing only the public methods
// note that we rename them here as well, making them easier to consume
const exp = {
h: publicHello,
hw: publicHelloWorld,
};
// export the object as default so it can be used in an unnamed import
export default exp;
to consume the module:
import whatever from "module.js";
whatever.h(); // "Hello"
whatever.hw(); // "Hello world"
What I have seen in most "es6 module how to" guides is this:
var utils = {
generateRandom: function() {
return Math.random();
},
sum: function(a, b) {
return a + b;
}
};
export default utils;