Home > database >  Does an imported file inherit the scope of its importer?
Does an imported file inherit the scope of its importer?

Time:04-25

When a file is imported in JavaScript, does that action cause the scope of variables in the imported file become that of the importer file, thus negating the necessity to add import declarations in the second imported file since they are declared in the importer file?

For example, if this is loaded first:

/* Config.js */
import { ImportantVar, OkayVar, LastVar } from 'first/file/path.js';
import DataObject from 'second/file/path.js';

and then this is loaded:

/* Second File */
export const DataObject = function( param1, param2 ) {
   return new ImportantVar( param1, param2 );
}

Should this line be added to the top of the second file?

import ImportantVar from 'first/file/path.js';

I don't care if the second file is broken should that it be run independently, i.e. not as an import from config.js.

CodePudding user response:

No. Every module has its own scope.

You're not "importing a file" or "importing the code to be run", you are importing the exported bindings of the module; the module stands on its own, and its exports can be imported in multiple places (while the code is only evaluated once). Inheriting scope wouldn't work with that.

So yes, you'll need to import { ImportantVar } from 'first/file/path.js' in your example.

  • Related