In Java, we have 4 visibility levels. Except public and private, we have protected level and a default level (with no modifier) that is also called "package-local" or "package-private".
| 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 |
See: https://www.programcreek.com/2011/11/java-access-level-public-protected-private/
I especially need this "package-private" level in Javascript. Is there a similar way for Javascript modules?
I'm writing a library (NPM package) and I want to export something (function, class, etc.) but not in the module's public API (to be used by consumers of the library). Just to be used locally between my module's files.
Node.js has an
exportsoption that is defined in "package.json": https://nodejs.org/api/packages.html#exportsIt can control which file(s) can be imported by the consumers (and how). It has a lot of options that unfortunately is not documented in the above official reference.
As an example, See "package.json" of my
smart-colorpackage:The above configuration causes the consumer to be able to
importthe file:"./lib/Color.js"this way:As other examples, see "package.json" of
dotenvpackage and "package.json" ofserver-onlypackage.