Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 export and import name functions?

I have some functions and I want to keep them in an external js file. eg.

in functions.js

var double = function(x) {
  return x + x;
}

export { double };

Then in my main js file:

import double from './functions';

...

double(2)

I get this error:

Uncaught TypeError: (0 , c.default) is not a function
    at bundle.min.js:44

When I read the line 44:

(0, _functions2.default)(2);

Any ideas why? What have I missed?

like image 924
Run Avatar asked Aug 04 '17 11:08

Run


People also ask

What is export default and named export in ES6?

Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas. They are es6 features.

How do I export multiple functions?

To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.

What is a named export?

What are Named Exports? Named exports allow us to share multiple objects, functions or variables from a single file and were introduced with the release of ES2015. Named exports are imported with curly braces in various files and must be imported using the name of the object, function or variable that was exported.

What are exports & imports in JavaScript?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.


Video Answer


2 Answers

You're confusing default and named exports.

If you export { double } you must import { double } from './functions';

If you only have one export, it's preferable to use the default export:

export default double;

Then you can import double from './functions':

The reason for this is that named exports allow you to import only part of a module. For example:

export function add (a, b) { return a + b; }
export function subtract (a, b) { return a - b; }

You can then import { add } from './math.js'; without importing subtract.

However, if you are only exporting one function from a module, the default export is more convenient.

like image 118
RyanZim Avatar answered Oct 17 '22 21:10

RyanZim


Use:

var double = function(x) {
  return x + x;
}

 export {double};

and

import {double} from './functions';

Or

export default double;

and

import double from "./functions.js";

like image 22
Carnaru Valentin Avatar answered Oct 17 '22 23:10

Carnaru Valentin