命名导出vs导出对象

Kar*_*son 13 javascript ecmascript-6

为什么这样做:

const str = 'stuff';
export {
  str
};
Run Code Online (Sandbox Code Playgroud)

但不是这个:

export default {
  str: 'stuff'
};
Run Code Online (Sandbox Code Playgroud)

我想将其导入如下:

import { str } from 'myLib';
Run Code Online (Sandbox Code Playgroud)

我想直接在导出中分配值,而不需要事先创建变量.

当我尝试时:

export {
  str: 'stuff'
};
Run Code Online (Sandbox Code Playgroud)

我收到错误:

SyntaxError: /home/karlm/dev/project/ex.js: Unexpected token, expected , (41:5)
  39 | 
  40 | export {
> 41 |   str: 'stuff'
     |      ^
  42 | };
  43 | 
Run Code Online (Sandbox Code Playgroud)

Sci*_*ter 10

ES6中有两种出口形式 - "正常"出口和默认出口.正常导出使用以下语法导出:

export const str = 'stuff';
// or
const str = 'stuff';
export {str};
Run Code Online (Sandbox Code Playgroud)

默认导出如下:

export default const str = 'stuff';
// or 
export default {
  str: 'stuff'
};
Run Code Online (Sandbox Code Playgroud)

导入时会显示差异.首先,你需要包括大括号:

import {str} from 'myModule'; // 'stuff', from the first example
Run Code Online (Sandbox Code Playgroud)

没有大括号,它会导入默认导出:

import myModule from 'myModule'; //  {str: 'stuff'}, from the second example
Run Code Online (Sandbox Code Playgroud)

  • 实际上,您不能默认导出变量声明。`export default const str ='stuff';`无效。 (2认同)