0
0
NodejsHow-ToBeginner · 4 min read

How to Use Import in Node.js: Syntax and Examples

In Node.js, you use the import statement to load modules when your project uses ES modules (ESM). To enable import, set "type": "module" in your package.json or use .mjs file extensions. Then you can import modules with import moduleName from 'module' syntax.
📐

Syntax

The import statement loads functions, objects, or primitives from another module. You can import the default export or named exports.

  • import defaultExport from 'module': imports the default export.
  • import { namedExport } from 'module': imports a specific named export.
  • import * as name from 'module': imports all exports as an object.

This syntax works only if Node.js treats your files as ES modules.

javascript
import defaultExport from 'module-name';
import { namedExport } from 'module-name';
import * as name from 'module-name';
💻

Example

This example shows how to use import in a Node.js ES module to load a function from another file and use it.

javascript
// mathUtils.mjs
export function add(a, b) {
  return a + b;
}

// app.mjs
import { add } from './mathUtils.mjs';

console.log(add(5, 3));
Output
8
⚠️

Common Pitfalls

Common mistakes when using import in Node.js include:

  • Not setting "type": "module" in package.json, so Node treats files as CommonJS and import fails.
  • Using .js files without the module type set, causing syntax errors.
  • Trying to import CommonJS modules with import without compatibility handling.

To fix, either add "type": "module" in package.json or rename files to .mjs. Also, use import() dynamic import for CommonJS modules if needed.

javascript
/* Wrong: no "type": "module" in package.json */
import fs from 'fs'; // SyntaxError: Cannot use import statement outside a module

/* Right: package.json includes "type": "module" */
import fs from 'fs'; // Works fine
📊

Quick Reference

Tips for using import in Node.js:

  • Set "type": "module" in package.json to enable ES modules.
  • Use .mjs extension if you don't want to set the type.
  • Use import for ES modules and require() for CommonJS modules.
  • Dynamic import: const module = await import('module-name'); for conditional or async loading.

Key Takeaways

Always set "type": "module" in package.json to use import syntax in Node.js.
Use import to load ES modules with clear syntax for default and named exports.
Use .mjs file extension as an alternative to setting the module type.
CommonJS modules require require() or dynamic import() for compatibility.
Dynamic import() allows loading modules asynchronously when needed.