Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

javascript - Named export vs exporting an object

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 | 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...