命名导出vs导出对象 [英] Named export vs exporting an object

查看:60
本文介绍了命名导出vs导出对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做:

  const str ='stuff'; 
export {
str
};

但不是这样:

 导出默认值{
str:'stuff'
};

我想将其导入如下:

 从'myLib'导入{str}; 

我想直接在导出中分配值,而不需要在创建变量之前另外,当我尝试时:

  export {
str:'stuff'
};

我收到错误:

  SyntaxError:/home/karlm/dev/project/ex.js:意外的令牌,预期,(41:5)
39 |
40 |出口{
> 41 | str:'stuff'
| ^
42 | };
43 |


解决方案

ES6中有两种出口方式 - 正常出口,默认出口。正常导出使用以下语法导出:

  export const str ='stuff'; 
//或
const str ='stuff';
export {str};

默认出口如下:

  export default const str ='stuff'; 
//或
导出默认值{
str:'stuff'
};

导入时会显示差异。对于第一个,你需要包括大括号:

 从'myModule'导入{str}; //'stuff',来自第一个示例

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

 从'myModule'导入myModule; // {str:'stuff'},来自第二个例子


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 | 

解决方案

There are two styles of exports in ES6 -- "normal" exports, and the default export. Normal exports get exported with syntax like this:

export const str = 'stuff';
// or
const str = 'stuff';
export {str};

Default exports go like this:

export default const str = 'stuff';
// 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

这篇关于命名导出vs导出对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆