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?
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.
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 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.
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.
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With