Import sub-modules (npm sub-path support)
When adding an npm module to a server script, you can optionally specify a sub-path to import a specific sub-module instead of the root package.
This allows you to:
-
Import only the functionality you need
-
Use modern Node.js APIs (e.g.
fs/promises) -
Match standard JavaScript import patterns such as
lodash/debounce
When a sub-path is provided when the module is added to the script, the server script runtime resolves the module as:
<module>/<sub-path>
The resolved export is exposed in the script via the configured module context name.
Examples
Named export
-
Module:
date-fns -
Sub-path:
format
const { format } = modules.datefns;
const result = format(new Date(), 'yyyy-MM-dd');
console.log(result);
| Some sub-modules expose named exports and must be accessed via restructuring. |
Default export (function)
-
Module:
lodash -
Sub-path:
debounce
const debounce = modules.lodash;
const log = (msg) => console.log(msg);
const debouncedLog = debounce(log, 300);
debouncedLog('hello');
Node.js built-in module
-
Module: fs
-
Sub-path: promises
const fs = modules.fs;
const content = await fs.readFile('/tmp/test.txt', 'utf8');
console.log(content);
Sub-path support preserves the original export behavior of each package. Always consume the module according to how it is defined by the package author.