Skip to content

Commit

Permalink
add an ESM version
Browse files Browse the repository at this point in the history
PR-URL: #266
Credit: @eugene1g
Close: #266
Reviewed-by: @isaacs

EDIT(@isaacs): edited to move the test into a test file, and run the
build before running tests, and specify TS types explicitly for both
export types, and document the hybridness.
  • Loading branch information
eugene1g authored and isaacs committed Feb 16, 2023
1 parent 724ee04 commit 4f6ba91
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 4 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -3,3 +3,4 @@
/nyc_output
/coverage
/bundle
/index.mjs
7 changes: 5 additions & 2 deletions README.md
Expand Up @@ -30,7 +30,10 @@ npm install lru-cache --save
## Usage

```js
const LRU = require('lru-cache')
// hybrid module, either works
import LRUCache from 'lru-cache'
// or:
const LRUCache = require('lru-cache')

// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
Expand Down Expand Up @@ -70,7 +73,7 @@ const options = {
fetchMethod: async (key, staleValue, { options, signal }) => {}
}

const cache = new LRU(options)
const cache = new LRUCache(options)

cache.set("key", "value")
cache.get("key") // "value"
Expand Down
22 changes: 20 additions & 2 deletions package.json
Expand Up @@ -10,7 +10,8 @@
],
"sideEffects": false,
"scripts": {
"build": "",
"pretest": "node ./scripts/transpile-to-esm.mjs",
"presnap": "node ./scripts/transpile-to-esm.mjs",
"size": "size-limit",
"test": "tap",
"snap": "tap",
Expand All @@ -20,7 +21,23 @@
"format": "prettier --write .",
"typedoc": "typedoc ./index.d.ts"
},
"main": "index.js",
"type": "commonjs",
"main": "./index.js",
"module": "./index.mjs",
"types": "./index.d.ts",
"exports": {
".": {
"import": {
"types": "./index.d.ts",
"default": "./index.mjs"
},
"require": {
"types": "./index.d.ts",
"default": "./index.js"
}
},
"./package.json": "./package.json"
},
"repository": "git://github.com/isaacs/node-lru-cache.git",
"devDependencies": {
"@size-limit/preset-small-lib": "^7.0.8",
Expand All @@ -41,6 +58,7 @@
"license": "ISC",
"files": [
"index.js",
"index.mjs",
"index.d.ts"
],
"engines": {
Expand Down
9 changes: 9 additions & 0 deletions scripts/transpile-to-esm.mjs
@@ -0,0 +1,9 @@
#!/usr/bin/env node

import { readFile, writeFile } from 'node:fs/promises'
const cjs = await readFile(
new URL('../index.js', import.meta.url),
'utf8'
)
const esm = cjs.replace(/module.exports\s*=\s*/, 'export default ')
await writeFile(new URL('../index.mjs', import.meta.url), esm, 'utf8')
10 changes: 10 additions & 0 deletions test/esm-load.mjs
@@ -0,0 +1,10 @@
import t from 'tap'
import LRUCache from '../index.mjs'
const c = new LRUCache({ max: 2 })
t.type(c, LRUCache)
c.set(1, 1)
c.set(2, 2)
c.set(3, 3)
t.equal(c.get(1), undefined)
t.equal(c.get(2), 2)
t.equal(c.get(3), 3)

0 comments on commit 4f6ba91

Please sign in to comment.