简体   繁体   English

尝试创建一个单独的文件,我可以在包含“new”的 JavaScript 中导入

[英]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.

相关问题 如何在单独的文件中创建一个javascript库并将其“包含”在另一个文件中? - How can I create a javascript library in a separate file and “include” it in another? 如何使用JavaScript创建新的文件夹/文件? - How can I create new folder/file with javascript? 我正在尝试将 SASS 变量导入到我的 javascript 文件中 - I am trying to import SASS variables into my javascript file 如何在同一个excel文件中将数据分隔到新工作表 - How can I separate data to new sheet in same excel file 在Javascript中创建新窗口时,为什么不能从JSON文件加载图像 - Why can't I load an image from a JSON file when I create a new window in Javascript 尝试在我的 Wordpress PHP 文件中将几个 Javascript 脚本排入队列后,如何防止“无法在模块外使用导入语句?” - After trying to enqueue several Javascript scripts in my Wordpress PHP file, how can I prevent “cannot use import statement outside a module?” 如何从单独的JavaScript文件中获取会话变量? - How can I get session variable from separate JavaScript file? 如何使用JavaScript永久修改单独文件上的JSON对象? - How can I permanently modify a JSON object on a separate file with JavaScript? Firebug - 如何运行多行脚本或创建新的JavaScript文件? - Firebug - how can I run multiline scripts or create a new JavaScript file? 我正在尝试使用 javascript new fileReader() 读取文件 - I am trying to read the file using javascript new fileReader()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM