简体   繁体   中英

Trying to create a separate file I can import in JavaScript with "new" involved

I have a object, cache declared as follows:

const cache = new InMemoryCache({);

I want to create a separate file the I can configure all the parameters that get passed into InMemoryCache({...}). When I create a new file called cache.js that looks like this,

export const cache = new InMemoryCache();

and then from my mail file, import it as `import {cache} from './cache.js'

I get different behavior then from my original code. I'm thinking I'm not getting what new is doing here. Suggestions?

new is used to create a new instance of an object (in this case, InMemoryCache ).
If you want to export this single instance that you defined using

const cache = new InMemoryCache({});

you need to make the export as

export { cache };

which will export the previously created instance.

If you also want to be able to create a new instance from elsewhere, you can export the constructor with

export { InMemoryCache };

(you can merge both exports together)

And then you can later import cache (the instance already defined), and InMemoryCache (the constructor) using

import { cache, InMemoryCache } from '<FILENAME>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM