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.
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).
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With