[英]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({...}).我想创建一个单独的文件,我可以配置传入 InMemoryCache({...}) 的所有参数。 When I create a new file called cache.js that looks like this,当我创建一个名为 cache.js 的新文件时,如下所示,
export const cache = new InMemoryCache();
and then from my mail file, import it as `import {cache} from './cache.js'然后从我的邮件文件中,将其导入为`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
). new
用于创建对象的新实例(在本例中为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然后你可以稍后导入cache
(已经定义的实例)和InMemoryCache
(构造函数)使用
import { cache, InMemoryCache } from '<FILENAME>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.