DEV Community

German Escobar
German Escobar

Posted on

Imports in Node.js

There are two main ways in which you can import code from another file (module):

  1. Import only the exports you are interested on (using curly braces)
  2. Import all the exports into an object (using import * as ...).

However, keep in mind that the option you choose can impact the way you name your exports.

If you are going to import only the exports you are interested on you may want to append more information to the name of each export. For example:

// users.service.js
export function listUsers() {}
export function createUser() {}

// controller.js
import { listUsers, createUser } from './users.service'
Enter fullscreen mode Exit fullscreen mode

On the other hand, if you are going to import all the exports into an object you can shorten the names of the exports

// users.service.js
export function list() {}
export function create() {}

// service.js
import * as userService from './users'
Enter fullscreen mode Exit fullscreen mode

It seems to me that userService.list() is a bit more clearer and simpler.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs