isaacs / node-lru-cache

A fast cache that automatically deletes the least recently used items
http://isaacs.github.io/node-lru-cache/
ISC License
5.35k stars 353 forks source link

Type error: 'LRUCache' can only be imported by using a default import #322

Closed vfarah-if closed 1 year ago

vfarah-if commented 1 year ago

As per the documentation on the README and the https://www.npmjs.com/package/lru-cache I created a very small POC to utilise this. When I compile it using yarn, there is no problem. When I build this using docker and external linters, I get this issue 13.63 ./pages/api/features/cache.ts:1:10 13.63 Type error: 'LRUCache' can only be imported by using a default import. 13.63 13.63 > 1 | import { LRUCache } from 'lru-cache'; 13.63 | ^

Can you suggest how I can over come this issue?

import { LRUCache } from 'lru-cache';
import { ONE_MINUTE_MS } from './constants';

const cache = new LRUCache({
  ttl: ONE_MINUTE_MS,
  allowStale: false,
  updateAgeOnGet: false,
  updateAgeOnHas: false,
  ttlAutopurge: true,
});

export default cache;
isaacs commented 1 year ago

You are getting an outdated version of lru-cache, or outdated types.

Run this in your target env where this happens:

npm ls lru-cache @types/lru-cache

you should not have the @types/lru-cache package present, and lru-cache should be latest version.

vfarah-if commented 1 year ago

I removed the @types/lru-cache, I refactored the code to use the * syntax e.g. and added in my tsconfig.json but that still did not seem to work

"esModuleInterop": true, "resolveJsonModule": true, "isolatedModules": true, "paths": { "@newlook/": [""] }, "typeRoots": ["./node_modules/@types"], "allowSyntheticDefaultImports": true

import * as Cache from 'lru-cache';
import { ONE_MINUTE_MS } from './constants';

const cache = new Cache.LRUCache({
  ttl: ONE_MINUTE_MS,
  allowStale: false,
  updateAgeOnGet: false,
  updateAgeOnHas: false,
  ttlAutopurge: true,
});

export default cache;
image
vfarah-if commented 1 year ago

Strange because I can see this here but yet I get this above issue. I also run the project locally with no problems with the caching, so all the functionality is perfect.

image
vfarah-if commented 1 year ago

I did also notice when I ran the command above that the output was slightly red, as a lot of libraries we use have your memory caching library. Do you think this may be the cause?

image
isaacs commented 1 year ago

Yep, those red lines are showing you some problems. Not sure why there's extraneous deps, but if something is expecting lru-cache@7 or and getting lru-cache@5 (or vice versa), you'd get this error.

I recommend using a package manager that is capable of resolving dependencies correctly for node's module system, such as npm.

isaacs commented 1 year ago

Also, lol, people really gotta update their lru-cache deps, you have practically every major version of it represented in your tree :joy: Luckily it's not very big.