https://github.com/dcodeio/esm2umd
Transforms ESM to UMD, i.e. to use ESM by default with UMD as a legacy fallback.
https://github.com/dcodeio/esm2umd
commonjs esm esmodules javascript umd
Last synced: 4 months ago
JSON representation
Transforms ESM to UMD, i.e. to use ESM by default with UMD as a legacy fallback.
- Host: GitHub
- URL: https://github.com/dcodeio/esm2umd
- Owner: dcodeIO
- Created: 2020-06-04T00:27:12.000Z (about 5 years ago)
- Default Branch: main
- Last Pushed: 2025-02-18T19:45:23.000Z (4 months ago)
- Last Synced: 2025-03-15T23:32:09.996Z (4 months ago)
- Topics: commonjs, esm, esmodules, javascript, umd
- Language: JavaScript
- Homepage:
- Size: 31.3 KB
- Stars: 6
- Watchers: 2
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
Awesome Lists containing this project
README
# esm2umd
Transforms ESM to UMD, i.e. to use ESM by default with UMD as a legacy fallback.
[](https://github.com/dcodeIO/esm2umd/actions/workflows/test.yml) [](https://github.com/dcodeIO/esm2umd/actions/workflows/publish.yml) [](https://www.npmjs.com/package/esm2umd)
## Usage
```
$> npm install --save-dev esm2umd
``````
npx esm2umd MyModule esmFile.js > umdFile.js
````MyModule` is used as the name of the vanilla JS global.
If the module has a `default` export, it is transformed to a whole-module export.
## API
```js
import esm2umd from "esm2umd";const esmCode = "...";
const umdCode = esm2umd("ModuleName", esmCode);
```## Examples
Common outline of a hybrid module with legacy fallback, either exporting a class or a namespace:
**package.json**
```json
{
"type": "module",
"main": "./umd/index.js",
"types": "./umd/index.d.ts",
"exports": {
".": {
"import": {
"types": "./index.d.ts",
"default": "./index.js"
},
"require": {
"types": "./umd/index.d.ts",
"default": "./umd/index.js"
}
}
},
"scripts": {
"build": "npx esm2umd MyModule index.js > umd/index.js && cp types.d.ts umd/types.d.ts"
}
}
```**umd/package.json**
```json
{
"type": "commonjs"
}
```**.gitignore**
```
umd/index.js
umd/types.d.ts
```### Class export
As used by [long.js](https://github.com/dcodeIO/long.js):
**index.d.ts**
```ts
import { MyClass } from "./types.js";
export default MyClass;
```**types.d.ts**
```ts
export declare class MyClass {
// ...
}
```**umd/index.d.ts**
```ts
import { MyClass } from "./types.js";
export = MyClass;
export as namespace MyClass;
```**umd/types.d.ts**
Copy of types.d.ts.
### Namespace export
As used by [bcrypt.js](https://github.com/dcodeIO/bcrypt.js):
**index.d.ts**
```ts
import * as myNamespace from "./types.js";
export * from "./types.js";
export default myNamespace;
```**types.d.ts**
```ts
export declare function myFunction(): void;
// ...
```**umd/index.d.ts**
```ts
import * as myNamespace from "./types.js";
export = myNamespace;
export as namespace myNamespace;
```**umd/types.d.ts**
Copy of types.d.ts.
## Building
Building the UMD fallback:
```
$> npm run build
```Running the [tests](./tests):
```
$> npm test
```