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

Adjusting the size of the snap increments

When using gridstack, I have the ability to resize my widgets. However, I've noticed that when dragging on the widgets' handles, they snap to specific sizes, which seems to be a fixed amount. If I wanted to set the widget's size to something ...

bespoke JavaScript confirmation dialogue box

After customizing a confirmation box for the logout feature, I encountered an issue. When the user presses cancel, the box closes and control remains on the same page as expected. However, when the user clicks yes to logout, nothing happens. Could anyone p ...

What is the reason for not displaying the various li elements on my webpage?

Here is the code snippet export default function DisplaySearchResults({ results }) { var arr = Object.entries(results) console.log(arr) return ( <div> Here are the search results : <ol> {arr.map((va ...

Differences between npm package "validator" and "express-validator"

Embarking on my Node JS journey, I find myself faced with two unfamiliar modules. Can anyone provide guidance on which validator is superior and more resource-efficient? validator: https://www.npmjs.com/package/validator express-validator: https://www.np ...

Can someone help me figure out this lengthy React error coming from Material UI?

Issues encountered:X ERROR in ./src/Pages/Crypto_transactions.js 184:35-43 The export 'default' (imported as 'DataGrid') could not be found in '@material-ui/data-grid' (potential exports include: DATA_GRID_PROPTYPES, DEFAULT ...

Polymer: Basic data binding is not functional in the second element

After dedicating 6 hours to this problem, I still can't seem to find a solution. Below is the code snippet from index.html: <flat-data-array availableModes="{{modes}}" id="dataArray"></flat-data-array> <flat-strip-view availableModes=" ...

Attempting to grasp the concept of implementing an If statement in conjunction with an event

Check out this HTML code snippet <body> <div> <button> Button A </button> <button> Button B </button> <button> Button C </button> </div> </body> This is my att ...

Automatically, the "ng-hide" class gets added despite using the correct syntax for ng-show

I am trying to dynamically show/hide a tr tag within a table based on the value of a scope variable in the controller. Despite writing the code correctly, I am facing an issue where the "ng-hide" class is automatically added to the tr tag every time it is ...

ReactAppI am facing an issue where the browser fails to refresh the page upon saving changes in my JavaScript file using the VS code editor

Can anyone remind me of the tool we can install to refresh the browser page automatically whenever we save changes in our editor? ...

Is there a way to simulate pressing a keyboard button using jQuery?

Below is the code snippet: $("input").on({ keydown: function(ev) { if (ev.which === 27){ // esc button backspace_emolator(); } else if (ev.which === 8){ // backspace button console.log('backspace button ...

What could be the reason the "npx expo start" command isn't functioning as expected?

Recently, I've encountered an issue with the npx expo start command while working on my amateur projects using Expo. Up until now, everything has been running smoothly with no complications. However, at this moment, the npx expo start command seems t ...

Reload a jquery pop up upon closing a pop up window

I have a modal pop up that appears after clicking an ASP button : <div class="form-group"> <asp:Button ID="btnBrand" runat="server" Text="Add brand" CssClass="btn btn-info" OnClick="btnAdd_Click" /> </div> Code Behind : protected ...

Is there a way to navigate to a newly created document?

Is there a way to automatically redirect a user to the show action of a document or post they have just created using express.js? Take a look at the following code snippet, which outlines how I am creating the document: app.post('/document/create&ap ...

What is the best way to retrieve the items stored within the array generated by a JavaScript function?

This particular function is responsible for calling a PHP script that outputs JSON data. It then iterates through the JSON object, creates a new object, and adds this new object to an array which is ultimately returned by the function. function getTestQues ...

Having trouble getting the jquery tabify plugin to work properly

I've put in a lot of effort and double-checked everything, but for some reason this tabify function just won't work. I have gone through my code 100 times but still can't seem to pinpoint the error. Here is the code I am working with: <! ...

Difficulties arise when attempting to install nodejs on linux using the npm install nodejs command

While attempting to execute... npm install nodejs I encounter the subsequent issue: npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: [email prot ...

What is the method for adding comments in package-scripts.js so that they appear in package.json?

Mission I am on a mission to showcase the comments of my nps commands from package-scripts.js in my package.json just like this: https://i.sstatic.net/cdeI4.png Attempted Solutions The source of this overlay message ("Run by the 'npm test' co ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Waiting to run a function until a specified function has finished its execution

I have a piece of code that needs to address synchronization issues related to the execution order of MathJax functions. Specifically, I need to ensure that all the MathJax operations are completed before running the setConsoleWidth() function. What is t ...

Persist user input even after reloading the page

In order to enhance the user experience, I would like to implement a feature where the data entered by the user is preserved even if they refresh, reload, or close the page. This includes retaining the selections made in the select elements. Additionally, ...