Share the constructor and enumeration in an npm module for exportation

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.

Answer №1

One way to handle the enum is by making it a property of the function object.

// myclass.js
// ...
MyClass.MyEnum = MyEnum;
module.exports = MyClass;

// elsewhere.js
let MyClass = require("myclass");
let x = new MyClass();
if (x.doWork() === MyClass.MyEnum.Success) { }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The express js backend (mongodb) is returning {error:{ }}

I'm learning how to POST Data to a Mongo DB using Express.js. Recently, I picked up Express.js for backend server development and this is my app.js const express = require("express"); const mongoose = require("mongoose"); require("dotenv/config") con ...

Striving to implement a dynamic dropdown menu using React's <select> element and rendering users from an array as selectable options

I am currently working on a project to develop an application that allows users to be added to a MongoDb database and have their names displayed in a dropdown menu. While creating the form, I encountered two issues - one related to the closing tag error a ...

Having trouble retrieving items from local storage in NextJS?

After logging in to my NextJS application, I store some user data in local storage. I'm attempting to create a small component that always shows the user's name. The problem I'm encountering is that sometimes it displays correctly and other ...

Unlocking React Event Handlers using Puppeteer

I'm struggling to fully comprehend my request, and I'm seeking clarification. I am currently working on scraping a website using Puppeteer in NodeJS. So far, I have managed to select the necessary element and access its properties. However, I am ...

Is there a way I can create a conditional statement to determine the values of my selection?

I need to customize the order status values for 'confirmed', 'on the way' and 'delivered'. How can I map these statuses to specific numerical values based on the options available in a select menu? Confirmed - 10 On the way - ...

Can lazy loading be implemented for the video tag using JavaScript?

Currently, I am in the process of working on a project that entails incorporating three videos onto the homepage. However, loading them simultaneously is causing a significant decrease in load time. In addition, I prefer to utilize the <video/> tag ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...

Customizing multi select in MUIv5 AutoComplete feature

My current challenge involves using the mui Autocomplete multi-select component. I'm having trouble getting it to function according to my specific requirements. Essentially, I need to set default selected values passed as props from the Parent compon ...

Issue with React redirect not functioning post transition

A component I created includes a redirection route that triggers after an animation finishes. Here is the code for reference: Menus.jsx class Menus extends Component{ constructor (props) { super(props); this.state = { select: 'esp ...

Using a combination of ASP.NET webpage and JavaScript, a dynamic webpage with a repe

I am new to using VB and integrating JavaScript. I have a simple question, but I'm having trouble figuring it out for some reason. I am struggling to properly construct an IF-statement. Can you please help me? I have searched and googled, but have no ...

Contrasting actions observed when employing drag functionality with arrays of numbers versus arrays of objects

Being a newcomer to D3 and JavaScript, I'm hoping someone can help me clarify this simple point. I am creating a scatter graph with draggable points using code that closely resembles the solution provided in this Stack Overflow question. When I const ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

Updating a database on ASP.NET without the need to refresh the page

We are developing a user-friendly application with ASP.NET MVC that focuses on uploading pictures and rating them. The app includes two voting buttons, "like" and "dislike". https://i.sstatic.net/Z3dp5.png Whenever the like button (green) is clicked, the ...

Transform tree-like JSON array with nested arrays into flat JSON array

I have an array tree in JSON format with potentially unlimited nesting: const namesArrayTree = [ { "name": "Peter" }, { "name": "folder1", "isArray": true, " ...

Create a filter system using a MERN stack that incorporates regex, a search box,

In an effort to understand how the MERN stack operates as a cohesive unit, I have taken on a hands-on approach by following tutorials from bezcoder. These include guides on Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code). Sam ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...

Utilizing a series of linked jQuery functions

Is there a more efficient way to write this code snippet? $('#element').html( $('#element').data('test') ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el ...

Using React Native to implement a slide bar that displays an image

Currently working on an app and aiming to implement a slider feature for emoji selection. Despite searching for suitable packages, I have not been able to find one that fits my requirements. As a result, I decided to use the react native slider instead. Ho ...

The issue of jQuery not functioning properly within a Rails environment

Despite my efforts, I am still struggling to make jquery work in rails. I have installed the 'jquery-rails' gem and added the require statements in the application.js file. Below is a sample test page that I have been testing: <!DOCTYPE htm ...

Having trouble with React JS BrowserRouter not routing correctly when used with Express JS and Nginx proxy

I am facing an issue where I need to send parameters to a React component through the URL. This works perfectly fine when I test it in my localhost development environment. However, the problem arises when I deploy the React app to my live server (). The ...