@ms-cloudpack/esm-stub-utilities
This library contains utilities for generating ESM stubs for CommonJS modules. Some bundlers require this for extracting named exports needed to produce a browser-compatible ESM bundle.
Usage
Call createESMStub
to generate a stub for the cjs entry:
import { createESMStub } from '@ms-cloudpack/esm-stub-utilities';
const esmStub = await createESMStub('/path/to/cjs/entry.js', '/path/to/esm/stub.js');
This call returns an esm stub string, but does not write the file. The path in the second argument is needed to derive import paths.
Example cjs file entry.js
:
module.exports = {
named1: 'named1',
named2: 'named2',
};
Example output (stub.js
):
import content from '../cjs/entry.js';
export {
default: content,
named1: content.named1,
named2: content.named2
};
To write the file in the same call, the writeESMStub
helper does this (which writes the stub to the node_modules/.cache folder in
the package):
import { writeESMStub } from '@ms-cloudpack/esm-stub-utilities';
const stubPath = await writeESMStub('./path/to/entry.js');
Special considerations
When evaluating named entries in the exports
of the cjs file, the library is loaded in the node process. A few libraries are used to simulate the browser environment in order for the script to load. (E.g. some libraries will reference window
on load, and therefore must be parsed in an environment that accommodates this.)
Libraries which export a default
entry in their exports
will have that value preserved as the default
export in the stub. However libraries which have an object exported which don't have a default
key will have the entire object exported as the default.
Libraries which export a function or literal value as the exports
result will have a default export for that entry.
Some libraries don't export anything. In this case, the stub will simply import the entry.
Exported members that are keywords will be ignored. (E.g. module.exports = { 'delete': "foo" };
would be considered an empty export.)