3 ms·
I've recently being helping a friend who is starting with Node.js, and I strongly recommended him (and anyone else getting started now) to use all `import` inst
by franciscop 5y ago
I've recently being helping a friend who is starting with Node.js, and I strongly recommended him (and anyone else getting started now) to use all `import` instead of `require`.
I would say it takes a bit more of work because the tutorials are normally written on commonJS (require), but otherwise it's just a different kind of work. Both of them have their peculiarities and issues, and CommonJS might also bite you big time. So if you have to choose, and both give you a bit of pain (for now), I'd suggest to choose the one that is more future-proof.
About the article on Esbuild and ESM vs CommonJS, some other personal notes:
- Node.js' `import` is more strict than frontend tools' `import`. You can do `import myfile from './myfile'` on the front-end but you need to specify the ".js" on the backend.
- You can no longer use __dirname with ES6 modules. That's a feature, and I found that I normally have enough control over where the script is run from that I just prefer write all relative paths instead of bothering shiming it.
- The Esbuild from the author is great and I use something similar for simpler projects and libraries I develop. However for making WebApps, I prefer to also have Hot Module Reload. It's like Prettier, at the beginning it feels unnatural and overbearing, but after you get used to it you realize what a huge order of improvement it is vs the way you were used to.
- ricardobeat 5y ago> CommonJS might also bite you big time In which ways? I’ve always found CommonJS to be extremely unsurprising. What will bite you is the tooling built to interoperate with ESM.
- franciscop 5y agoIn the way that some libraries have been updated to be ESM-only, so if you follow a tutorial to-the-letter and then try to require() that library it'll fail with a cryptic error message (at least for new users).
- merrywhether 5y agoFWIW, you can replace __dirname with information from import.meta (and 2 lines of JS). It’s not quite as automagic but can yield the exact same info. You’re also right that it might just be a code-smell in general though.
- franciscop 5y agoYeah, I've had 2 layers of deception there. You think it might be those 2-3 lines from the popular StackOverflow answer, but after hunting a bug for a while I realized that it was url-encoding that space in the path name and saying "directory doesn't exist" when in the console it was obviously correct. Drove me crazy until I realized in the full path there was, early in the path, a single "%20" and my JS senses told me it doesn't make sense for spaces to be url-encoded in paths.