As a Node engineer, I am happy with common.js (cjs) and find it has a nice simplicity. That said EcmaScript Modules (ESM) are the way of the future.
The Fast and Easy ESM for NodeJs
Sometimes we just need a clean, fast, and easy solution. If you would like to learn more about the history and why ESM is really a better option than cjs scroll down. Now, let's get into the code!
After running your
npm init command, in your package.json file, add in the main object (directly under "main" is a great place, but not required):
If you are a React developer, then ESM is common and part of your daily coding life. If not, how you import and export are slightly different from the traditional way of doing it in NodeJs.
Now to import in ESM all the exports above,
- First, they help to keep your code organized. By putting related code into separate modules, you can avoid having a giant mess of code in one file. This makes it easier to find what you're looking for and makes your code more maintainable in the long run.
- Second, modules make your code more reusable. If you have a piece of code that you want to use in multiple projects, you can simply import the module into each project instead of copying and pasting the code each time.
- Finally, modules can make your code more reliable. If one module contains a bug, you can simply update that module without needing to worry about breaking other parts of your codebase.
If you're interested in learning more about Node.js, especially for backend development, I recommend CodeDamn. They have great content, playgrounds, and even a free web development bootcamp!