snippetjavascriptMinor
how to properly expose an ES class function residing inside a module?
Viewed 0 times
exposeproperlymodulefunctionresidinghowclassinside
Problem
I have a little class for loading a config file:
And I test it like so:
It works, but I'm wary of including a capitalized property in
// index.js:
class Config {
constructor(path) {
this.path = path || this.defaultPath;
this.config = fs.readFileSync(this.path, { encoding: 'utf8' });
this.config = JSON.parse(this.config);
}
get() {
return this.config;
}
}
Config.prototype.defaultPath = './config/config.json';
module.exports = {
Config: Config,
};And I test it like so:
// test.js:
const index = require('../index');
let config;
describe('config ', () => {
before(() => {
config = new index.Config().get();
});
});It works, but I'm wary of including a capitalized property in
module.exports (mostly because I haven't seen this done before). Is there a best practice for achieving this in other ways? Should I just make the config class into its own .js file?Solution
I'm not aware of any best practice here, so this answer is my own hunch.
I would stick with using an uppercase 'C' for the exported member name.
In JavaScript, the usual protocol is to use an uppercase name for a function that should be
to show that the function should be used with a
As you are exposing a class from your module, in other words a function that can be new'd up from, then I would stick with using a capital
I would stick with using an uppercase 'C' for the exported member name.
In JavaScript, the usual protocol is to use an uppercase name for a function that should be
new from, rather than called directly e.g.function Config()to show that the function should be used with a
new call, to treat it as a constructor. e.g.var config = new Config();As you are exposing a class from your module, in other words a function that can be new'd up from, then I would stick with using a capital
C.Context
StackExchange Code Review Q#148755, answer score: 2
Revisions (0)
No revisions yet.