Because it doesn't work for Node.js due to the dynamic nature of JavaScript.
Supposed, a module defined a constant data
. Then it would need to export this, as part of its event-emitting API. Something such as:
const data = 'data';
class Api extends EventEmitter () {
constructor () {
setTimeout(() => {
this.emit(data);
}, 2 * 1000);
}
}
module.exports = {
data,
Api
};
Then, from the outside we would have something such as:
const foo = require('./foo');
const { Api, data } = foo;
const api = new Api();
api.on(data, () => {
// ...
});
Basically, something like this. Now what if you mistyped data
in the beginning? What if instead of
const { Api, data } = foo;
you mistyped:
const { Api, Data } = foo;
It would work, without any error. Data
would just be undefined
. You don't get an error in JavaScript when you try to access an object's property that does not exist, you just get back undefined
.
So, you won't get a compiler error, but now you're emitting (under the hood) 'data', but what you're listening for is undefined
. The constant does not help in any way, you still have to make sure that you do not mistype its name.
And that is in no way better or worse than using a string where you are not allowed to mistype anything.
So, to cut a long story short, constants don't improve the situation, they just lead to more typing and make things more complicated - but they don't solve any real problem.