1

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?

Michael
  • 53
  • 5
  • 1
    "*the console of file A*" - a file doesn't have a separate console. You get a single global `console` for each execution environment (e.g. webpage, or `node` application). – Bergi Mar 18 '21 at 23:35
  • 2
    "*does the entire file that has been exported from run in the file importing*" - no, the exporting module runs **before** the importing module, in its own scope. And notice that it only runs once to initialise, no matter how often/where you import it. – Bergi Mar 18 '21 at 23:37
  • 1
    https://exploringjs.com/es6/ch_modules.html https://medium.com/backticks-tildes/introduction-to-es6-modules-49956f580da https://exploringjs.com/impatient-js/ch_modules.html – Bergi Mar 18 '21 at 23:39

2 Answers2

2

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.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
-2

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();
  • It doesn't answer the question. The question is not how to export and import files. OP wanted to know if the files run when imported. – Zsolt Meszaros Mar 26 '21 at 22:02