This is something I've wondered for a while now. Say I have an express application. I have this export in its own file:
// my-var.js
export const myVar = new Thing();
Then I have the server creation where I access that variable:
// index.js
import { myVar } from './my-var';
import { myRoutes } from './my-routes';
function startServer() {
myVar.doSomething(); /* 1 */
const app = express();
app.use('/', myRoutes);
app.listen(port, () => {});
}
Finally, I have my routes, which also use that variable:
// my-routes.js
import { Router } from 'express';
import { myVar } from './my-var';
const router = new Router();
router.get((req, res) => {
myVar.doSomething(); /* 2 */
res.json({});
});
So my question is: Is .1 and .2 referencing the same variable? Or has it been instantiated twice? I would kind of think it's instantiated every time the file is imported, because importing a file runs the code in that file. So myVar = new Thing();
is executed every time that file runs.