Because this does not work for Node.js due to the dynamic nature of JavaScript.
Suppose the module defines the constant data
. Then he will need to export this as part of his event-generating API. Sort of:
const data = 'data'; class Api extends EventEmitter () { constructor () { setTimeout(() => { this.emit(data); }, 2 * 1000); } } module.exports = { data, Api };
Then from the outside we will have something like:
const foo = require('./foo'); const { Api, data } = foo; const api = new Api(); api.on(data, () => {
Basically, something like this. Now, what if you made a mistake at the beginning of data
? What if instead
const { Api, data } = foo;
you are mistaken:
const { Api, data } = foo;
This will work without errors. data
will only be undefined
. You will not get an error in JavaScript when you try to access an object that does not exist, you will simply return undefined
.
So, you will not get a compiler error, but now you are emitting (under the hood) data, but what you are listening to is undefined
. The constant does not help in any way, you still need to make sure that you are not mistaken in the name.
And this is no better or worse than using a string where you are not allowed to make any mistakes.
So, in order to shorten the long story, constants do not improve the situation, they simply lead to a larger typing and complicate the situation, but they do not solve any real problems.