Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript import all modules from a file as a global variables

Tags:

javascript

In script1.js, I have the following exports:

export function test1() {
  // do something
}

export function test2() {
  // do something
}

I am importing script1.js into script2.js:

import * as functions from './script1.js';

functions.test1();
functions.test2();

I am wondering if there is a way to import all the modules from script1.js, and directly place them inside the global variables of script2.js. So I can directly access them with test1(), test2(), without the intermediate step of putting them in an object.

I know that we can do import {test1, test2} from './script1.js';, but if I have a lot of exports, then the deconstruction will be tedious.

In another word, what I am looking for is something equivalent of:

import * from './script1.js';

test1();
test2();

The above code block is hypothetical, and it does not work.

like image 373
Chen Avatar asked Jun 25 '26 04:06

Chen


2 Answers

Given your current code, it's not possible. The whole point of modules is to avoid implicit global pollution. To do something like this, you'd have to explicitly assign the functions to the global object inside the module, eg, change:

export function test1() {
  // do something
}

to

window.test1 = function test1() {
  // do something
};

and then, when the module is imported, the functions will be available globally:

import './script1.js';

But this is an antipattern:

but if I have a lot of exports, then the desconstruction will be tedious.

It does require some boilerplate, but don't be afraid of it - in larger projects, having explicit dependency chains is a huge plus for maintainability. It also permits tree-shaking, which isn't possible for modules with side-effects only (like assigning to the global object).

like image 133
CertainPerformance Avatar answered Jun 26 '26 19:06

CertainPerformance


you can also very simply auto generate the import , with a script like this:

import * as functions from './script1.js';

const function_names = Object.keys(functions).join(',')

console.log( function_names ) //output: test1,test2

your list is ready in your console!

like image 32
Babak Karimi Asl Avatar answered Jun 26 '26 17:06

Babak Karimi Asl