My background in NPM and Node.js is limited, as my expertise lies mainly in JavaScript for web browsers. Recently, I created a JavaScript library that consists of a constructor function and an enum type.
In JavaScript, enums do not exist natively, so the JS file I wrote follows this structure:
function MyClass() {
// Implementation
this.doWork = function () {
// ...
return MyEnum.Success;
};
}
var MyEnum = {
Error: 0,
Success: 1,
Something: 2,
More: 3
// etc.
// Object.define could be used to make it constant
};
The MyClass
function uses properties from MyEnum
internally and it's also beneficial for the user of MyClass
. Therefore, it should remain public.
In an npm package, only either properties within the main object can be exported, or the object itself. Here are potential solutions:
module.exports = MyClass;
Or
module.exports = {
MyClass: MyClass,
MyEnum: MyEnum
};
In the first scenario, using the class directly is simple but MyEnum
becomes inaccessible.
let MyClass = require("myclass");
let x = new MyClass();
// How can I access MyEnum?
The second option requires specifying the class name twice when using it.
let MyClass = require("myclass");
let x = new MyClass.MyClass();
if (x.doWork() === MyClass.MyEnum.Success) { }
I am seeking advice on how to address this issue and ensure that the constructor is readily available while also exporting the enum.