ES6在多个位置导入文件,为什么文件一次加载? [英] ES6 import a file in multiple place, why the file loads once?

查看:296
本文介绍了ES6在多个位置导入文件,为什么文件一次加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个名为common.js的公共文件,还有其他文件,例如a.jsb.js ...

If there has a common file named common.js, and others such as a.js, b.js...

common.js

const Common = { property: 'initial' }
export { Common };

a.js

import { Common } from 'common.js';
Common.property = 'changed';

b.js

import { Common } from 'common.js';
console.log(Common.property);

首先,运行a.js并将common.js加载到内存中.

First, a.js runs and load the common.js into memory.

然后,b.js由引擎运行.

  1. common.js是否会再次加载或使用内存中现有的common.js?
  2. 如果common.js是由其他xx.js脚本更新的,import的行为将如何?
  1. Does the common.js will load again or use the existing common.js in the memory?
  2. If common.js was updated by other xx.js script, how will the import behave?

推荐答案

我假设您正在使用Node.js,因此import在编译后将变成require语句.

I'm assuming you are using Node.js so the import will turn into require statements after transpiling.

从文档中

模块在第一次加载后被缓存.这意味着(除其他事项外)每次对require('foo')的调用都将返回完全相同的对象,如果它可以解析为相同的文件.

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

来源

要明确回答您的问题:

  1. 模块已缓存,因此您要更改同一对象
  2. 它将打印最后分配的值
    • 例如changed如果执行了a.js
    • 如果仅执行b.js,则它将打印initial
  1. The module is cached so you are changing the same object
  2. It will print the the last value assigned
    • for example changed if a.js was executed
    • if only b.js is executed, then it will print initial

在线试用此处.

这篇关于ES6在多个位置导入文件,为什么文件一次加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆