Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> either naming your file `.mjs`

But why? This makes it much harder to ensure that identical code works in browser and nodejs, to the point where I sometimes just can't use nodejs. And I don't use package.json, so having to name files ".mjs" is a really painfull restriction.



Browsers will happily accept `.mjs` files they don't actually care about file extensions only about `Content-Type` and type=module on the script tag :]


Plenty of (third-party) imports specifically reference "*.js" files so no, this doesn't work.


why are you writing node applications without using package.json?

it sounds like you're looking to have a problem with javascript tbh. don't use it, whatever


There is absolutely no need for a package.json when using ES6 imports without a build step. Package.json doesn't do anything when I'm loading the code in a browser, why would I have to use it when I want to run the same JS code with node?


this is a silly point. it's a different runtime, there are also different apis available - as is the point of this article. node is not an internet browser. but ok


If you're hosting the browser-based version over a server like Apache2 (to host the files), you could add a `RewriteRule` to redirect queries to `.js` resources to their `.mjs` counter-part files.

Example: RewriteRule "(.*).js$" "$1.mjs" [R=301 NC]

Reference documentation: https://httpd.apache.org/docs/2.4/rewrite/intro.html




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: