JavaScript: Share module contents internally through exporting

When working with Java, there are 4 different visibility levels to consider. In addition to the commonly known public and private levels, there is also the protected level and what is referred to as the "default" or "package-local" level.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y X
no modifier Y Y X X
private Y X X X

For more information on Java access level comparisons, visit:


In my JavaScript projects, I find myself needing a similar "package-private" level of visibility. Are there any equivalents for this in JavaScript modules?

Currently, while developing a library (which will eventually be published as an NPM package), I am looking for a way to export certain functions or classes internally within the module, without them being part of the public API intended for consumer use.

Answer №1

How to Divide a TypeScript NPM Package into Separate Files Without Revealing Internal Parts

One way to achieve this is by using package.json to determine what gets exported from the npm package. While everything can still be accessed within the project, explicit importing ensures that only the specified components are exposed to other projects consuming the package.

Answer №2

Within Node.js, there is an important exports option specified in the "package.json" file: https://nodejs.org/api/packages.html#exports

This option allows control over which files can be imported by consumers and how they can be accessed. Despite not being fully documented in the official reference provided above, it offers a plethora of choices.


For instance, take a look at the "package.json" for my smart-color package:

"exports": {
  "./*" : "./lib/*",
  "./Color" : "./lib/Color.js",
  "./ColorCustomInspect" : "./lib/ColorCustomInspect.js",
  "./convertors" : "./lib/convertors.js",
  "./luminance" : "./lib/luminance.js",
  "./luminanceInverter" : "./lib/luminanceInverter.js",
  "./recolorFilter" : "./lib/recolorFilter.js",
  "./web-colors" : "./lib/web-colors.js"
},

This particular configuration enables consumers to import the file: "./lib/Color.js" in this manner:

import Color from 'smart-color/Color' // Instead of '.../lib/Color[.js]'

For additional examples, refer to the "package.json" of the dotenv package and the "package.json" of the server-only package.

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

What is the best way to access HTML attributes within a JavaScript function when working with a dynamic element?

When a user interacts with an HTML element on my website, I aim to display the attributes of that specific element in a new browser tab. An example of such an HTML element is: <a id="d0e110" onclick="GetWordFile(this.id)" attr1="attr1_value" attr2="at ...

Is it possible to move the res.send() outside of the function in node.js?

I currently have the following code: var server = http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'}); var oo = require('/test.js'); oo(connection, function (e, res ...

Incorporate a specialized module assistant within the template file of a separate module

After developing a new module connected to another database, I attempted to call the helper class from a different module template file named "description.pthml". The code I used is as follows: $_helper = $this->helper('ForumProdPosts/output' ...

Jenkins does not have the capability to execute npm or pm2 independently

Currently, I have a Jenkins CI setup running on an EC2 server. I've successfully installed nodejs and npm. Interestingly, Jenkins is able to access them via the command line using this command: sudo -u jenkins node -v However, when it comes to actua ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

When the page is dynamically loaded, Ng-repeat does not function as expected

I am working on a page that includes the following code snippet: <script> angular.module('myapp', []).controller('categoryCtrl', function($scope) { $scope.category = <? echo json_encode($myarr); ?>; $scope.subcatego ...

Is it possible to limit the values of parameters with react-router?

Currently, I am in the process of developing a website using react and react-router. I have two different types of routes set up, as shown below: <Route name="products" path="/:type/*" handler={ ProductList } /> <Route name="generic-template" p ...

Show text upon hovering using jQuery

I am currently exploring jquery and trying to implement a functionality where text is displayed upon hovering over a div element. My basic html page consists of squares, with one of them rotating when a button is clicked. I now want to show some text withi ...

return to the original secured page based on the most recent language preference

I'm facing an issue with a logical redirection that needs to redirect users to the previous protected page after login. The login functionality is implemented using my custom login page and Google Credentials. Additionally, I have set up a multilingu ...

Alter the div's HTML content once the Ajax operation is completed

I have a div element that looks like this: <div class="progress" id="progress-bar"></div> I am using the following JavaScript code along with an ajax call to retrieve some data. The data returned is 0, however, the content is not being added ...

Component fails to re-render after token refresh on subsequent requests

Here is my axios-hoook.js file, utilizing the axios-hooks package. import useAxios from 'axios-hooks'; import axios from 'axios'; import LocalStorageService from './services/local-storage.service'; import refreshToken from &ap ...

Encountering a 404 error in Angular MVC project while trying to load a

Trying to access an edit partial named AddEditPersonModal.cshtml from a different folder in my MVC project, in order to load its contents into a UI Bootstrap modal using Angular. However, when the index.cshtml page loads, I encounter a 404 error related to ...

What is the best way to set up v-models for complex arrays or nested objects?

I'm looking to efficiently create multiple v-models for random properties within a deep array, where the position of attributes in arrays/objects can change dynamically. While I've managed to achieve my goal with the current setup, I'll need ...

Please enter the password to install jest using yarn add command

While attempting to install yarn add jest in the work repository I cloned onto my machine, I encountered an error. C:\COMPANY_NAME\Work-Folder\frontend>yarn add jest yarn add v1.13.0 [1/4] Resolving packages... [2/4] Fetching packages.. ...

The npm ping feature is causing command prompt windows to open

I am currently working on a project that involves pinging certain IPs. I have opted to use the npm ping package for this purpose, which can be found at https://www.npmjs.com/package/ping. Initially, when I run the service, everything works perfectly fine. ...

Error Encountered: Unable to locate package.json file upon running npm audit fix

Trying to install sass but keep encountering an issue that I don't understand. The error message appears like the one shown in the image I know I should execute the command npm audit fix, but every time I try, it gives me an error saying "no package. ...

Failed to send JSON data to WebMethod

I am encountering difficulties while attempting to send JSON to a WebMethod. I have provided the method I am using below. If there is a more efficient approach, please advise me. My goal is to store the JSON object in a database. JavaScript function TEST ...

Exploring the Touch Feature in Angular

I am facing an issue with touch events as I am not receiving any useful X/Y coordinates. The event object does not provide the necessary information I need for touch events (https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches). Despi ...

Populate an array using a callback function within an async.series operation

I have a callback function within 'async.series' that generates multiple values and creates various outputs from 'elements'. Is there a way to save these return values into an array using 'forEach'? async.series( { ...

When utilizing AJAX within a for loop, the array position may not return the correct values, even though the closure effectively binds the scope of the current value position

Is this question a duplicate of [AJAX call in for loop won't return values to correct array positions? I am following the solution by Plynx. The issue I'm facing is that the closure fails to iterate through all elements in the loop, although the ...