# Node Polyfill Plugin

:::tip About Node Polyfill
Normally, we don't need to use Node libs on the browser side. However, it is possible to use some Node libs when the code will run on both the Node side and the browser side, and Node Polyfill provides browser versions of polyfills for these Node libs.
:::

By using the Node Polyfill plugin, Node core libs polyfills are automatically injected into the browser-side, allowing you to use these modules on the browser side with confidence.

## Quick Start

### Used in Modern.js framework

The Modern.js framework integrates the Builder's Node Polyfill plugin by default, so you don't need to manually install and register the plugin, just set the [output.disableNodePolyfill](https://modernjs.dev/configure/app/output/disable-node-polyfill.html) config to `false`:

```js
export default defineConfig({
  output: {
    disableNodePolyfill: false,
  },
});
```

### Use via the Node API

If you use the Builder's Node API, you need to manually install and register the esbuild plugin.

#### Install

You can install the plugin with the following command:

```bash
# npm
npm install @modern-js/builder-plugin-node-polyfill -D

# yarn
yarn add @modern-js/builder-plugin-node-polyfill -D

# pnpm
pnpm add @modern-js/builder-plugin-node-polyfill -D
```

#### Register

Register node polyfill plugins through the `addPlugins` method:

```js
import { builderPluginNodePolyfill } from '@modern-js/builder-plugin-node-polyfill';

// add the plugin to the builder instance
builder.addPlugins([builderPluginNodePolyfill()]);
```

## Node Polyfills

### Globals

- `Buffer`
- `process`

When the above global variables are used directly in code, the corresponding polyfill will be injected.

```ts
const bufferData = Buffer.from('xxxx');
```

### Modules

- `assert`
- `buffer`
- `console`
- `constants`
- `crypto`
- `domain`
- `events`
- `http`
- `https`
- `os`
- `path`
- `punycode`
- `process`
- `querystring`
- `stream`
- `_stream_duplex`
- `_stream_passthrough`
- `_stream_readable`
- `_stream_transform`
- `_stream_writable`
- `string_decoder`
- `sys`
- `timers`
- `tty`
- `url`
- `util`
- `vm`
- `zlib`

When the above module is referenced in code via import / require syntax, the corresponding polyfill will be injected.

```ts
import { Buffer } from 'buffer';

const bufferData = Buffer.from('xxxx');
```

### Fallbacks

- `child_process`
- `cluster`
- `dgram`
- `dns`
- `fs`
- `module`
- `net`
- `readline`
- `repl`
- `tls`

Currently there is no polyfill for the above modules on the browser side, so when you import the above modules, it will automatically fallback to an empty object.

```ts
import fs from 'fs';

console.log(fs); // -> {}
```
