3 ms·
It's not possible to eliminate unused code safely with CommonJS. require is entirely dynamic and can be used in arbitrary ways. It's impossible to analyse all s
by jahewson 11y ago
It's not possible to eliminate unused code safely with CommonJS. require is entirely dynamic and can be used in arbitrary ways. It's impossible to analyse all such uses correctly, after all JS is Turing complete, so you're going to have to solve the halting problem first! In practice, this issue doesn't come up much, but some modules do use dynamic loading.
The same applies to module.exports, the final set of exports from a module can only be determined by executing that module. While you can spot common patterns, ultimately JS is, again, Turing complete, so the code has to be executed. In practice, this is frequently an issue as modules often use sophisticated logic to build up their exports.
So it's impossible to statically analyse all such dynamic modules, which is why the ES6 module system is static. This is a big win as it allows tree-shaking to be done with 100% safety.
Also note that the ES6 import syntax opens up future possibilities which are not possible by destructuring require, for example type annotations look set to come to JS and destructuring can't be used to import a type, because types are not values.
- spb 11y agoConsidering that anything more complex than a primitive in JS is implemented as a prototype chain attached to a first-class-function constructor, I'd say that, in JS, types are absolutely values.