1

I want to import a function in my js file. Here is a simple code:

// In index.js file
function addition(a, b) {
    return a + b;
}

export { addition };

// In test.js file

import { addition } from "./index.js";

console.log(addition(5, 4));

The result in the console: enter image description here

Thanks !

Mohamed Zahour
  • 338
  • 2
  • 15

2 Answers2

2

NodeJS uses CommonJS Module syntax which doesn't support import/export, but instead requires to use module.exports like so:

// In index.js file
function addition(a, b) {
    return a + b;
}

module.exports = addition;

// In test.js file

const addition = require("./index.js");

console.log(addition(5, 4));
Phoenix1355
  • 1,589
  • 11
  • 16
  • "NodeJS uses CommonJS Module syntax" — Only by default. It supports ES6 modules and the error message explains how to use them. – Quentin Aug 31 '21 at 12:45
  • @Quentin, it indeed does, but it seems like he runs Node directly on the javascript file, and from that, I assume he isn't using an NPM project at all with a package.json, which is required for the solution suggested in the error to work. – Phoenix1355 Aug 31 '21 at 12:47
  • 1
    I will mark your question as better question. – Mohamed Zahour Aug 31 '21 at 12:48
  • @Phoenix1355 — There's no evidence in the question, one way or other, about the existence of a `package.json` file. It's required for *one* of the two solutions in the error to work. It could be created if it doesn't already exist. – Quentin Aug 31 '21 at 12:49
0

To use the modern import/export syntax with NodeJS you have to set your package type to module in the package.json file, like you are told in the console output.

https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs

Festlandtommy
  • 112
  • 1
  • 8