Top level code can be executing multiple times if many entry points

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-11-21

// file1.js

export myfunc() {
  console.log("hello")
}

documentReady(myfunc)

// file2.js
import { myfunc } from  "./file1"

Both file1 and file2 were added as script tags. I then saw "hello" twice in the Chrome Dev Tools console.

Why? because two copies of module in the project. This normally doesn't happen with one entry point, becuase the interpreter can calculate if a module is already loaded. But this isn't possible in this situation.