/

How to Use Import in Node.js

How to Use Import in Node.js

If you are using Node.js and want to switch from using require() to the ES modules import syntax, here’s how you can do it:

  1. Open your package.json file.
  2. Add "type": "module", to the JSON object like this:
1
2
3
4
5
6
{
"name": "projectname",
"type": "module",
"version": "1.0.0",
...the rest of your file
}

Save the file and you’re done! Now you can use import to import modules in your Node.js code. For example:

1
import fs from 'fs'

By making this change, you can take advantage of the modern ES modules syntax in your Node.js projects. Enjoy coding!

Tags: Node.js, import, require, ES modules