Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why importing * from a file execute the code?

Why exporting nothing from a file (or module), renamed it and just put the variable in the scope execute the code?

// log.js
console.log('A message');
// index.js
import * as app from 'log.js';

app;

Result: A message gets printed, as expected. But if you comment out the app line:

// log.js
console.log('A message');
// index.js
import * as app from 'log.js';

// app;

Nothing gets printed. What's going on here?

There is an example using codesandbox: https://codesandbox.io/s/xenodochial-keldysh-j0sli

Update: I did't realize it was the typescript example I added to the question, I was doing test using typescript and javascript: here's the codesandbox for the js version: https://codesandbox.io/s/silly-oskar-0mo2o

like image 857
Sergio Flores Avatar asked Sep 25 '26 16:09

Sergio Flores


1 Answers

This is expected Typescript behavior. See Why are imports being elided in my emit? and this thread on Typescript's github.

TypeScript assumes that module imports do not have side effects, so it removes module imports that aren't used in any expression.

Without the app namespace being used, Typescript doesn't even bother trying to import and run log.js because the namespace isn't being used anywhere and it assumes the module has no side effects, so there's no point importing it.

If you do want to assert that importing alone should have side effects, use:

import 'log.ts';

This results in the top-level code of log.ts being logged as expected.

Note that this is a Typescript-specific behavior. outside of Typescript, top-level code of a module does run whenever the module is imported, regardless of what was imported or referenced later.

like image 60
CertainPerformance Avatar answered Sep 28 '26 05:09

CertainPerformance