Skip to content

Commit

Permalink
refactor!: cleanup defineEnv and docs (#434)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Feb 10, 2025
1 parent e2daf94 commit 4e36629
Show file tree
Hide file tree
Showing 8 changed files with 272 additions and 304 deletions.
113 changes: 44 additions & 69 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,90 +7,71 @@

<!-- /automd -->

unenv provides a collection of Node.js and Web polyfills and mocking utilities with configurable presets for converting JavaScript code and libraries to be platform and runtime agnostic, working in any environment including Browsers, Workers, Node.js, Cloudflare Workers, Deno.

Unenv is used by [Nitro](https://nitro.unjs.io/) and [Nuxt](https://nuxt.com/) today.

> [!NOTE]
> You are on the development (v2) branch. Check out [v1](https://github.com/unjs/unenv/tree/v1) for the current release.
## Install

<!-- automd:pm-i dev -->

```sh
# ✨ Auto-detect
npx nypm install -D unenv

# npm
npm install -D unenv

# yarn
yarn add -D unenv

# pnpm
pnpm install -D unenv
unenv, provides (build-time) polyfills to add [Node.js](https://nodejs.org/) compatibility for any JavaScript runtime, including browsers and edge workers.

# bun
bun install -D unenv
## 🌟 Used by

# deno
deno install --dev unenv
```

<!-- /automd -->
- [Nitro](https://nitro.build/)
- [Nuxt](https://nuxt.com/)
- [Cloudflare](https://developers.cloudflare.com/workers/runtime-apis/nodejs/)
- [ESM.sh](https://esm.sh/)

## Usage

Using `env` utility and built-in presets, `unenv` will provide an abstract configuration that can be used in bundlers ([rollup.js](https://rollupjs.org), [webpack](https://webpack.js.org), etc.).
The `defineEnv` utility can generate a target environment configuration.

```js
import { defineEnv } from "unenv";

const { env } = defineEnv({
nodeCompat: true,
resolve: true,
presets: [],
overrides: {},
/* options */
});

const { alias, inject, polyfill, external } = env;
const { alias, inject, external, polyfill } = env;
```

**Note:** You can provide as many presets as you want. unenv will merge them internally and the right-most preset has a higher priority.

## Presets

### `node`

[(view source)](./src/presets/node.ts)
You can then integrate the env object with your build tool:

Suitable to convert universal libraries working in Node.js.
| Bundler | `alias` | `inject` | `external` |
| -------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
| rollup | [`@rollup/plugin-alias`](https://www.npmjs.com/package/@rollup/plugin-alias) | [`@rollup/plugin-inject`](https://www.npmjs.com/package/@rollup/plugin-inject) | [`external`](https://rollupjs.org/configuration-options/#external) |
| rolldown | [`resolve.alias`](https://rolldown.rs/reference/config-options#resolve-alias) | [`inject`](https://rolldown.rs/reference/config-options#inject) | [`external`](https://rolldown.rs/reference/config-options#external) |
| vite | [`resolve.alias`](https://vite.dev/config/shared-options#resolve-alias) | [`@rollup/plugin-inject`](https://www.npmjs.com/package/@rollup/plugin-inject) | [`ssr.external`](https://vite.dev/config/ssr-options#ssr-external) |
| esbuild | [`alias`](https://esbuild.github.io/api/#alias) | [`inject`](https://esbuild.github.io/api/#inject) | [`external`](https://esbuild.github.io/api/#external) |
| rspack | [`resolve.alias`](https://rspack.dev/config/resolve#resolvealias) | - | [`externals`](https://rspack.dev/config/externals#externals-1) |
| webpack | [`resolve.alias`](https://webpack.js.org/configuration/resolve/#resolvealias) | [`webpack-plugin-inject`](https://www.npmjs.com/package/webpack-inject-plugin) | [`externals`](https://webpack.js.org/configuration/externals/#externals) |

- Add supports for global [`fetch` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
- Set Node.js built-ins as externals
**Note:** You can provide as many presets as you want. unenv will merge them internally and the right-most preset has a higher priority.

```js
import { env, node } from "unenv";
### Options

const envConfig = env(node, {});
```
- `nodeCompat`: Add `alias` entries for node builtins both as `id` and `node:id` + `inject` entries for Node.js globals
such as `global`, `Buffer`, and `process` (default: `true`).
- `npmShims`: Add `alias` entries to replace common NPM packages such as `node-fetch` with native Web APIs (default: `true`).
- `presets`: Additional presets (for example [`@cloudflare/unenv-preset`](https://npmjs.com/@cloudflare/unenv-preset/).
- `overrides`: Additional overrides for env config.
- `resolve`: Resolve config values to absolute paths (default: `false`).

### `nodeless`
### Using direct imports

[(view source)](./src/presets/nodeless.ts)
You can also directly import `unenv/` polyfills:

Suitable to transform libraries made for Node.js to run in other JavaScript runtimes.
| Polyfills | Description | Source |
| ---------------- | ------------------------------------------ | -------------------------------------------------------------------------------------- |
| `unenv/mock/*` | Mocking utils | [`src/runtime/mock`](https://github.com/unjs/unenv/tree/main/src/runtime/mock) |
| `unenv/node/*` | APIs compatible with `Node.js` API | [`src/runtime/node`](https://github.com/unjs/unenv/tree/main/src/runtime/node) |
| `unenv/npm` | NPM package shims for lighter replacements | [`src/runtime/npm`](https://github.com/unjs/unenv/tree/main/src/runtime/mock) |
| `unenv/polyfill` | Global polyfills | [`src/runtime/polyfill`](https://github.com/unjs/unenv/tree/main/src/runtime/polyfill) |
| `unenv/web` | Subset of Web APIs | [`src/runtime/web`](https://github.com/unjs/unenv/tree/main/src/runtime/web) |

```js
import { env, nodeless } from "unenv";
## Node.js compatibility

const envConfig = env(nodeless, {});
```

## Built-in Node.js modules
`unenv` replaces Node.js built-in modules compatible with any runtime [(view source)](./src/runtime/node).

`unenv` provides a replacement for Node.js built-in modules compatible with any runtime.
<details>

<!-- automd:file src="./coverage/unenv.md" -->

Expand Down Expand Up @@ -151,19 +132,13 @@ const envConfig = env(nodeless, {});

<!-- /automd -->

[(view source)](./src/runtime/node)

## Package replacements

`unenv` provides a replacement for common npm packages for cross-platform compatibility.

[(view source)](./src/runtime/npm)
</details>

## Manual mocking utils

```js
// Magic proxy to replace any unknown API
import MockProxy from "unenv/runtime/mock/proxy";
import MockProxy from "unenv/mock/proxy";

// You can also create named mocks
const lib = MockProxy.__createMock__("lib", {
Expand All @@ -173,14 +148,12 @@ const lib = MockProxy.__createMock__("lib", {

[(view source)](./src/runtime/mock)

## Other polyfills

To discover other polyfills, please check [./src/runtime](./src/runtime).

## Nightly release channel

You can use the nightly release channel to try the latest changes in the `main` branch via [`unenv-nightly`](https://www.npmjs.com/package/unenv-nightly).

<details>

If directly using `unenv` in your project:

```json
Expand All @@ -201,6 +174,8 @@ If using `unenv` via another tool (Nuxt or Nitro) in your project:
}
```

</details>

## License

<!-- automd:contributors license=MIT author=pi0 -->
Expand Down
43 changes: 17 additions & 26 deletions lib/index.d.mts
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
/**
* Configure a target environment.
*
* @example
* ```ts
* const { env } = defineEnv({
* nodeCompat: true,
* resolve: true,
* presets: [myPreset],
* overrides: {}
* });
*/
export declare function defineEnv(opts?: CreateEnvOptions): {
env: Environment;
Expand All @@ -17,19 +8,29 @@ export declare function defineEnv(opts?: CreateEnvOptions): {

export interface CreateEnvOptions {
/**
* Enable Node.js compatibility (nodeless) preset.
* Node.js compatibility aliases.
*
* Default: `false`
* Default: `true`
*/
nodeCompat?: boolean;

/**
* NPM compatibility aliases.
*
* Default: `true`
*/
npmShims?: boolean;

/**
* Additional presets.
*/
presets?: Preset[];

/**
* Additional overrides.
*/
overrides?: Partial<Environment>;

/**
* Resolve paths in the environment to absolute paths.
*
Expand All @@ -48,17 +49,13 @@ export interface EnvResolveOptions {
}

export interface Environment {
alias: {
[key: string]: string;
};
inject: {
[key: string]: string | string[];
};
polyfill: string[];
external: string[];
alias: Readonly<Record<string, string>>;
inject: Readonly<Record<string, string | readonly string[] | false>>;
polyfill: readonly string[];
external: readonly string[];
}

export interface Preset {
export interface Preset extends Partial<Environment> {
meta?: {
/**
* Preset name.
Expand All @@ -73,10 +70,4 @@ export interface Preset {
*/
readonly url?: string | URL;
};
alias?: Environment["alias"];
inject?: {
[key: string]: string | string[] | false;
};
polyfill?: Environment["polyfill"];
external?: Environment["external"];
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"types": "./lib/index.d.mts",
"default": "./dist/index.mjs"
},
"./package.json": "./package.json",
"./mock/proxy-cjs": {
"types": "./lib/mock.d.cts",
"default": "./lib/mock.cjs"
Expand Down
Loading

0 comments on commit 4e36629

Please sign in to comment.