4 ms·
> Not clear to me why just using 'import' makes it a module and 'require' not. I'm sure that's spelled out somewhere I'm probably wrong but I think it has to d
by mstade 8y ago
> Not clear to me why just using 'import' makes it a module and 'require' not. I'm sure that's spelled out somewhere
I'm probably wrong but I think it has to do with parsing rules. If you try to load a module as CJS and hit incompatible syntax (e.g. keywords such as import or export) then it has to restart parsing from the top. Likewise, if you parse the file as ESM but hit CJS syntax such as `exports.foo = bar` then again it has to restart.
There are probably a bunch of similar issues but if I recall correctly it basically came down to parsing and performance, you don't want to load the same thing twice essentially. With a special extension you don't have to even load the file before deciding which parsing rules to use, supposedly making this more efficient.
I've heard several proposals to resolve this issue, but my favorite two are probably the unambiguous module syntax and making import/require only compatible with their respective module formats. The first would be a breaking syntactic change, in that every ESM module would be required (no pun intended) to include the top level `export` keyword at least once, regardless of whether or not the module actually exports anything. The second would be to make node's `require` function only compatible with CJS modules and make the `import` keyword only compatible with ESM. Both of these have drawbacks of course, but I'd like to think they're mostly temporary and rather easily overcome. The unambiguous module syntax less so perhaps, but still.
- cwmma 8y agothe other issue was that a module that doesn't import, export or require anything and doesn't specify strict mode will get parsed differently depending on whether it is a CJS or an ESM and their is no in band way of telling which is which
- mstade 8y agoThat’s right, thanks for the reminder! Some syntax is ambiguous yet results differ. I think that’s why I liked the unambiguous module syntax very much, it made things explicit, without much cost.