Reputation:
I have an electron app (Running typescript compiled to es6) and I'm trying to do some relatively simple window management. My only problem is that it seems to be duplicating the variable that I am trying to store all the windows in.
A simplified version of the class system looks like this:
// index.js
const { app } = require('electron');
const { Project } = require('./project');
const { Window } = require('./Window');
function createWindow() {
console.log("");
}
app.on('ready', createWindow);
// window.js
console.log("Creating new map!!!!");
const windows = new Map();
class Window {
static createWindow(name) {
windows.set(name, "0");
}
}
module.exports = {
Window
};
// project.js
const { Window } = require("./window");
class Project {
}
module.exports = {
Project
};
What I would expect the output to be is just:
Creating new Map!!!!
But instead I get two maps:
Creating new Map!!!!
Creating new Map!!!!
This ends up giving me weird behavior, because I want the windows map variable to act like a static variable that is attached to the Window class, meaning there is only ever one instance of it, but I have tried so many different ways and can't seem to get that to work.
Does anyone know how to avoid this weird duplication of variables when using multiple require statements?
Here's the package.json in case anyone wants to duplicate this behavior.
// package.json
{
"name": "testproj",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "electron .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^12.12.2",
"electron": "^7.1.7"
}
}
Upvotes: 0
Views: 374
Reputation: 5531
This happens because for Node.js require
'./window
and'./Window
(with capital W in the begin)is different.
Caching is case sensitive and considers them different. Thus the file is parsed twice as you noticed.
You can check what's happening with
console.log(require.cache)
You'll see window
and Window
as keys for two different Objects
{ ...
'path/to/window.js': Module { ... }
'path/to/Window.js': Module { ... }
}
Some readings about the topic
Upvotes: 1