There are two ways to include a library in Node:
- Using CommonJS
- Using ES Modules
CommonJS
Common JS (or CJS) is Node’s original way to include packages. If you want to include a library in Common JS, you use the require keyword.
const path = require('path')ES Modules
ES Modules (or ESM) is the current standard way to import packages both in frontend JavaScript and Node.
If you want to include a library with ESM, you use the import statement.
import path from 'path'Using ESM over CJS
We’re going to use ESM over CJS because ESM is now the preferred way to include packages.
Note: ESM packages are not backward compatible with CJS. This means CJS is becoming obsolete as prolific developers (like Sindresorhus) build ESM only packages.
There are more differences between ESM and CJS, but we won’t be covering them since it’s out of the scope of this course. We’ll only touch on what’s needed (which is everything you need 90% of the time).
Supporting ESM
The simplest way to support ESM is to set type to module in the package.json file.
{ "type": "module"}That’s it!
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson