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 exports
option that is defined in "package.json":
https://nodejs.org/api/packages.html#exports
It 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-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"
},
The above configuration causes the consumer to be able to import
the file: "./lib/Color.js"
this way:
import Color from 'smart-color/Color' // Not from '.../lib/Color[.js]'
As other examples, see "package.json" of dotenv
package and "package.json" of server-only
package.