alice
alice

Reputation: 55

Import JS file to make its variables part of the global scope of file that is importing them?

So I have a js file (1) filled with variables and I want to import all the variables from the file (1) to another js file (2), for organization purposes, so that these variables make part of the global scope of the js file (2).

I tried "import/export * from [path]" with no success. I can import individual files with the export/import but then I have to call it with "importName.variable" which ends up making the process more complicated with more variables.

I know I could just add the script files to the html as tags and I would get the desired results, but are there any downsides to putting the script files on the html instead of importing them from the js files? Is this the only way of doing what I want?

Thanks in advance.

Upvotes: 4

Views: 2365

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371233

With ES6 modules, the only way to do something like this would be to make the variables completely global. In the other file, do something like:

window.someVarName = 'someValue';

Otherwise, you'll have to write out all the values explicitly when importing, eg:

export const someVarName = 'someValue';
import { someVarName } from './theFileName.js';

The second approach is highly recommended. Having an explicit dependency chain makes code a lot more manageable. It might take a bit longer to write, but in large applications, it'll make things so much easier to maintain.

There's no way to make variables exported in one file visible to the whole contents of another file without

  • making the variables global everywhere, or
  • explicitly importing the variables, either individually or as the whole module's namespace

are there any downsides to putting the script files on the html instead of importing them from the js files?

Yes, it'll make the variables global everywhere, which will make a large application more difficult to maintain and understand.

Upvotes: 1

Related Questions