Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript export / import doesn't work

it might be a silly question but I can't fix it anyway. I have a JavaScript file with various functions I'd like to export.

export function AddNumbers(...numbers)
{
    let value = 0;

    for(var i = 0;i < numbers.length;i++)
    {
        value += numbers[i];
    }

    return value;
}  

When I call this method (using mocha) I get an error message "export function AddNumbers(...numbers) Unexpected token export". The project is build as ES6. Does anybody know what I'm doing wrong?

Best regards, Torsten

like image 432
zimmybln Avatar asked Dec 31 '25 09:12

zimmybln


2 Answers

You need to use module.exports as NodeJS uses CommonJS Module syntax which requires to use module.exports and not just export which is defined by ES6 module syntax. So, make sure CommonJS is also configured properly in your project.

like image 167
Ankit Agarwal Avatar answered Jan 02 '26 23:01

Ankit Agarwal


Another solution is to use Babel. Install it with

npm install babel-core --save-dev
npm install babel-preset-es2015 --save-dev

Create in root directory a file .babelrc with following content

{
    "preset" : ["es2015"]
}

and finally change the script in package.json to run into:

"scripts": {
    "test": "mocha Tests --require babel-core/register"
}

and now export / import works.

like image 40
zimmybln Avatar answered Jan 02 '26 23:01

zimmybln



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!