Why does this work:
const str = 'stuff';
export {
str
};
But not this:
export default {
str: 'stuff'
};
I'd like to import it as the following:
import { str } from 'myLib';
I'd like to assign the value directly in the export and not require having to create a variable before hand.
Also when I try:
export {
str: 'stuff'
};
I get the error:
SyntaxError: /home/karlm/dev/project/ex.js: Unexpected token, expected , (41:5)
39 |
40 | export {
> 41 | str: 'stuff'
| ^
42 | };
43 |
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.
export { variable as default } exports the reference to the exported variable , whereas with export default variable , the importing modules do not receive the reference to the exported variable .
If you categories exports as 'export of domestic goods' and export of 'foreign goods', the difference between export and re export makes easier to follow. In simple terms, exports mean export of domestic goods moved out to a foreign country.
Use named exports to export a component in React, e.g. export function Button() {} . The exported component can be imported by using a named import as import {Button} from './another-file. js' . You can use as many named exports as necessary in a file.
There are two styles of exports in ES6 -- named exports, and the default export. Named exports get exported with syntax like this:
export const str = 'stuff';
// or
const str = 'stuff';
export { str };
Default exports go like this:
const obj = { str: 'stuff' };
export default obj;
// or
export default {
str: 'stuff'
};
The difference shows up when you import. With the first, you need to include braces:
import { str } from 'myModule'; // 'stuff', from the first example
Without braces, it imports the default export:
import myModule from 'myModule'; // {str: 'stuff'}, from the second example
The main reason of the export statement is to be used to export functions, objects or primitives from a given file (or module).
But you need an identifier in order to be exported (so that it can be imported via import
in another script).
You can simply do:
export const obj = {
str: 'stuff'
};
During the import, you will be able to use the same name obj
to refer to the corresponding value.
And import it like:
import { obj } from 'myLib';
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