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?

3
  • 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). Commented Mar 18, 2021 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. Commented Mar 18, 2021 at 23:37
  • 1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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();

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.