简体   繁体   中英

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?

An example being:

File A:

import {func} from 'fileB.js';

File 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. For example, would it be when the import statement is run, or when the func is called. 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?

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

declare like this

const Logger = function() {

}
export { Logger };

use it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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