DEV Community

Arbaoui Mehdi
Arbaoui Mehdi

Posted on

4 2

Use the ES6 import in Node.js

If you decide to use the ES6 import instead of require, this is a simple presentation on how to achieve that using babel:

– First Install the core dependencies:

npm install babel-register babel-preset-env --save-dev
Enter fullscreen mode Exit fullscreen mode

– Create a starter.js file that contain how your code has to be transpiled plus the file that contains your imports:

require("babel-register")({
  presets: ["env"],
});

// Import the rest of our application.
module.exports = require("./test.js");
Enter fullscreen mode Exit fullscreen mode

And now your can use import in your test.js file instead of require:

import validator from "validator";

const email = "yep";

if (!validator.isEmail(email)) {
  console.log("the email is not valid");
}
Enter fullscreen mode Exit fullscreen mode

To test the output:

node starters.js
Enter fullscreen mode Exit fullscreen mode

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 (3)

Collapse
 
sonicoder profile image
Gábor Soós

It is supported natively

Collapse
 
arbaoui_mehdi profile image
Arbaoui Mehdi

Not for the older versions.

Collapse
 
dimitir profile image
Dmitriy Popovich

Hi! Thank for article. Do you know way to use ES6 modules in node with typeScript?

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