DEV Community

loading...

Use the ES6 import in Node.js

arbaoui_mehdi profile image Arbaoui Mehdi 🇲🇦 ・1 min read

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

– 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");

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");
}

To test the output:

node starters.js

Discussion (3)

pic
Editor guide
Collapse
vuesomedev profile image
Gábor Soós

It is supported natively

Collapse
arbaoui_mehdi profile image
Arbaoui Mehdi 🇲🇦 Author

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?