by BillinghamJ · 7y ago · 0 comments
The index.js thing is nice, but I think consistency with browsers is more important and I'd be willing to lose it.
There's no browser standard about .mjs. In fact the web doesn't really notice file extensions; it goes by media types and attributes. A browser knows that something is JavaScript because it is served with the application/javascript media type (or similar), and it knows it is a module because the <script> element has a type=module attribute.
A lot of the talk about "browser equivalence" is extremely loosely worded and leads people to think that .mjs is a browser thing, but it's not. It's a Node thing. What they want is for code to work the same way whether it's running on Node or running in a browser. The problem they face is that Node hasn't got the type attribute to decide whether something is a module or not, so they can't use the same mechanism the browser has.
The solution they have devised is to assume that .mjs is a JavaScript module and .js is not. The consequence is that if you want the same code to work in Node and on the web, you've got to change what happens on the web to follow the Node idea of naming things .mjs. Otherwise when you import a module named .js – which works in the browser – it will fail in Node. So this isn't about making Node match what happens in the browser, it's about making what happens in the browser match the Node approach, which is not a standard in any sense.
To share code between the browser and server you have to update the server config to set the Content-Type header to text/javascript when serving .mjs files.
According to the WHATWG HTML spec [1]:
> Servers should use text/javascript for JavaScript resources. Servers should not use other JavaScript MIME types for JavaScript resources, and must not use non-JavaScript MIME types.
Although I'll admit I was surprised to see them suggesting you use text/javascript instead of application/javascript. I've been using application/javascript for years, since I don't have to support old versions of Internet Explorer.
[0] https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_...
[1] https://html.spec.whatwg.org/multipage/scripting.html#script...