4 ms·
ES6 modules are great because they're statically analysable, whilst CommonJS modules aren't.
by allover 10y ago
ES6 modules are great because they're statically analysable, whilst CommonJS modules aren't.
- z3t4 10y agojust parse it like any other js code
- tomatsu 10y agoDeclarations can be analyzed statically. Declarative stuff is convenient that way. If you have to execute code, things get messy.
- allover 10y agoBy that do you mean you can 'just parse' CommonJS modules? (If so) CommonJS allows you to dynamically alter module.exports anywhere within your module. You can't determine what those exports are just by parsing, you'd need to execute the code.
- nailer 10y ago> CommonJS allows you to dynamically alter module.exports anywhere within your module It's certainly a risk, but that isn't a common practice.
- z3t4 10y agoThere's also ... if(Math.round(Math.random()) === 1) { export let foo = bar; // have fun debugging! } I think it would also be fine to execute modules to see what's in module.exports, while some modules might have side effects like writing to /etc/passwd without calling any method, it's not the norm.
- allover 10y ago> There's also ... [...] (I assume you meant to write your example in CommonJS style, because that's not valid a ES6 export, they must be top-level). Doesn't your example highlight exactly why even executing the code wouldn't even help you there?
- z3t4 10y agoDidn't know you could only export at the global scope. Wanted to show that you could do stupid, hard to analyze things in ES6 modules too. But maybe you can't !? Although I don't want a committee to not only decide what is stupid or not, but also hard code it into the spec so I can't do some things even if I have very good reasons to. Like being able to require modules locally to make the code easier to reason about, and easier to delete, copy, share, reuse and manage. It's what made NodeJS so popular, because it's so easy to use, reuse and share modules.
- bakkoting 10y ago> Wanted to show that you could do stupid, hard to analyze things in ES6 modules too. But maybe you can't !? You can't, at least not in this way. A module's imported and exported names are statically determined. Of course, you can just export a single object, and then make that object arbitrarily complex depending on runtime behavior. > Like being able to require modules locally Not sure what this means.
- z3t4 10y agolocally: inside functions
- allover 10y agoThe fact it's allowed at all is the problem though, and precisely why ES6 modules are superior.
- lhorie 10y agoYou can statically analyze CommonJS modules (and they are most often used in a statically optimizable way), they just aren't statically optimizable in the general case.