简体   繁体   English

在 Javascript 中导入

[英]Importing in Javascript

When one imports a specific value from another file, does the entire file that has been exported from run in the file importing?当从另一个文件导入特定值时,导出的整个文件是否在文件导入中运行? For example if I wanted to import the function "hello" from file b, into file a, would file b run in file a?例如,如果我想将文件 b 中的 function "hello" 导入文件 a,文件 b 会在文件 a 中运行吗?

An example being:一个例子是:

File A:档案一:

import {func} from 'fileB.js';

File B:文件 B:

let func = function(){...}
console.log(`Hello`);
export {func};

Would Hello appear in the console of file A, and if it would, under what circumstances. Hello会出现在文件 A 的控制台中吗,如果会出现,在什么情况下会出现。 For example, would it be when the import statement is run, or when the func is called.例如,是在运行 import 语句时,还是在func时。 If it would not run, are there any ways to make it so it does.如果它不会运行,有什么方法可以让它运行。 For example if I exported the entire file (if that's possible) would the Hello appear under certain circumstances?例如,如果我导出了整个文件(如果可能的话), Hello在某些情况下会出现吗?

The imported file will be run.将运行导入的文件。 An easy way to both understand and remember this is dynamic exports :理解和记住这一点的一种简单方法是动态导出

export let Foo;

if (window.Foo === undefined) {
  Foo = class Foo { ... }
} else {
  Foo = window.Foo;
}

In order to know what was exported to begin with, the code needs to be run.为了知道开始导出的内容,需要运行代码。 Otherwise, it would be equal to solving the halting problem.否则,这将等于解决停机问题。

if you are using webpack import or require如果您使用 webpack 导入或要求

declare like this像这样声明

const Logger = function() {

}
export { Logger };

use it用它

import { Logger } from '../class/Logger';
let logger = new Logger();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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