这是一个React组件,它使用json文件中的值来呈现内容:
import React from 'react';
import jsonFile from 'file.json';
const Component = ({ thing }: { thing: string }) => {
return (
<div>
...json file is used in here...
</div>
);
};
应用运行时,该组件将被多次调用。
Does jsonFile
get reimported every time the component is called? What about classes, abstract classes, etc.? Is there ever a situation in React or in general where every new instance/call of a class/component causes a reimport to occur or are imports always loaded once before code execution?
我觉得后者是正确的答案,但我希望您能提供解释或链接,以了解与此相关的进口行为。
欢迎来到StackOverflow!您几乎是正确的,但是您缺少一件事:您几乎可以肯定使用捆绑器,因此导入是在构建时而不是运行时解决的。
ECMAscript 6 code (including classes, arrow functions, and even that import statement) is not supported by many browsers and only support pure JavaScript files. Moreover, JSX syntax is not supported in browsers because it's not a part of the ECMAscript spec. There are other issues too, such as the fact that you can only import a
.js
file and nothing else.由于这些原因,大多数现代Web应用程序(例如您自己的Web应用程序)都使用称为捆绑程序的工具将ES6转换为兼容的,广泛支持的ES5。捆绑程序对您的代码做了很多事情(例如缩小),但是其中一个步骤是获取这些外部依赖关系并将其添加到您的代码中。
如果您有特殊的逻辑,则可以从技术上以多种方式执行此操作(即在运行时下载它们-这称为代码拆分),但是大多数人在构建时使用默认方法-解析。
What all this means is that when you import
file.json
, before your browser runs it, your bundler findsfile.json
in the filesystem and embeds the JSON contents into the JavaScript file. For example, this means if you update it on your server without rebuilding, it will not change in the browser. As a side-effect, it means that reimporting the same file (or in this case, JSON file) will not cause any slowdown.A few extra notes: your original premise that the JSON file would be reimported by using the component multiple times is a bit flawed because even if none of this bundler stuff happened, the file would be imported into the
jsonFile
variable and stored in memory; nothing in the component would cause a re-import since the variable is already defined.最后,TypeScript是JavaScript的超集,但仅在构建时产生影响:如果它可以静态地检测到您错误地使用了类型,则它会引发编译错误;但是,如果没有错误,则在运行时不进行动态检查;它只是将代码转换为纯JavaScript。因此,除了在类型错误的上下文中,无需提及使用TypeScript,因为它在运行时与JavaScript相同。
希望这一切都能为您解决!