MrKleeblatt
MrKleeblatt•2y ago

`await import()` without global execution

Hello there. This is some code from my test.ts:
// test.ts
console.log("Hello World");
export const say_hi = ()=>console.log("hi");
// test.ts
console.log("Hello World");
export const say_hi = ()=>console.log("hi");
When I import test.ts via
// main.ts
const mod = await import("test.ts");
// main.ts
const mod = await import("test.ts");
the code inside test.ts will be executed and I get Hello World to the console. Is it possible that I import only exported code from test.ts and do not run any of it intrinsically?
4 Replies
Andreu Botella (they/them)
no, because test.ts could do something like this:
let test = Math.random();
export default function() {
test += 1;
return test;
}
let test = Math.random();
export default function() {
test += 1;
return test;
}
nayeemrmn
nayeemrmn•2y ago
^ Instead you should wrap your top-level test.ts code in if (import.meta.main) {} assuming that's what you want.
abi
abi•2y ago
Maybe you already considered this, but it seems like a bad idea in general to import things from a test module
MrKleeblatt
MrKleeblattOP•2y ago
Oh, this seems like a misunderstanding 😅 test.ts is just some random file, has nothing to do with actual tests. But thanks @Andreu Botella (he/they), that's what I assumed as well…