Skip to content

Commit

Permalink
Add instructions for dynamic import in README.md (#516)
Browse files Browse the repository at this point in the history
* Add instructions for dynamic import in README.md

* Split into ul and add example

* Make example code block more clear

* Cache dynamic import in example
  • Loading branch information
YitzchakMeltz authored Jan 8, 2025
1 parent 078b605 commit 5681219
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,8 @@ Test configuration: Framework 13 7840U, Fedora 39, Node.js 21.6.
npm install nanoid
```

### ESM
Nano ID 5 works with ESM projects (with `import`) in tests or Node.js scripts.
For CommonJS `require()` you need to use latest Node.js 22.12
(works out-of-the-box) or Node.js 20 (with `--experimental-require-module`):

For Node.js 18 you can use Nano ID 3.x (we still support it):

```bash
npm install nanoid@3
```

For quick hacks, you can load Nano ID from CDN. Though, it is not recommended
to be used in production because of the lower loading performance.
Expand All @@ -149,6 +142,25 @@ to be used in production because of the lower loading performance.
import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
```

### CommonJS
Nano ID 5 can be used with CommonJS in one of the following ways:

- You can use `require()` to import Nano ID. You need to use latest Node.js 22.12 (works out-of-the-box) or Node.js 20 (with `--experimental-require-module`)

- For Node.js 16 or newer you can dynamically import Nano ID as follows:
```js
let nanoid;

module.exports.createID = async () => {
if (!nanoid) ({ nanoid } = await import('nanoid'));
const id = nanoid() // => "V1StGXR8_Z5jdHi6B-myT"
}
```

- You can use Nano ID 3.x (we still support it):
```bash
npm install nanoid@3
```

## API

Expand Down

0 comments on commit 5681219

Please sign in to comment.