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 !

3
  • The error message flat out tells you two different solutions to this problem!! Commented Aug 31, 2021 at 12:44
  • 1
    Does this answer your question? JavaScript export / import doesn't work Commented Aug 31, 2021 at 12:44
  • 1
    Yes @Phoenix1355! Commented Aug 31, 2021 at 12:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

"NodeJS uses CommonJS Module syntax" — Only by default. It supports ES6 modules and the error message explains how to use them.
@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.
I will mark your question as better question.
@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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.