What is use of Curly Braces in ES6 import statemen

2019-01-03 10:07发布

I can see there are two different ways to import

import React from 'react'
import { render } from 'react-dom'

the second one has brackets. So what is the difference between the two? and when should I add brackets? thanks

标签: reactjs redux
4条回答
The star\"
2楼-- · 2019-01-03 10:52

Consider primitives.js,

export default (a, b) => a + b;
export const sub = (a, b) => a - b;
export const sqr = a => a**2;

it can be imported like this,

import sum, { sub, sqr } from './primitives';

In this case, sum is called a "Default Export" and a module may contain a single "Default Export" only.

sub and sqr are called "Named Export" and a module may contain multiple named exports.

查看更多
放我归山
3楼-- · 2019-01-03 10:53

Curly Braces are used to import single(specific) property, whereas the word without braces is import entire object form that file.

Eg.,

import React, { Component } from 'react';

Here the word React represents to import entire object from the file 'react'

{Component} means we specify to import the particular property from the file.

查看更多
劫难
4楼-- · 2019-01-03 10:55

No need to add bracket if you exporting as default. you can have only default in the module.

case1:

export default function(num1, num2) { return num1 + num2; }

case2:

function sum(num1, num2) { return num1 + num2; }

export { sum as default };

case3:

function sum(num1, num2) { return num1 + num2; }

export default sum;

you can import the default

import sum from "./test.js";

console.log(sum(1, 2));

查看更多
孤傲高冷的网名
5楼-- · 2019-01-03 11:04

Well the difference between whether you should import your components within brackets or without it lies in the way you export it.

There are two types of exports

  1. Default Export
  2. Names Export

A component can have one default export and zero or more named exports

If a component is a default export then you need to import it without brackets E.g.

export default App;

The import it as

import App from './path/to/App';

A named export could be like

export const A = 25;

or

export {MyComponent};

The you can import it as

import {A} from './path/to/A';

or

import {A as SomeName} from './path/to/A';

If your component has one default export and few named export, you can even mix them together while importing

import App, {A as SomeName} from './path/to/file'; 

Similarly in case of react and react-dom, React and ReactDOM are default exports respectively whereas, for instance Component is a named export in react and render is a named export in react-dom. Thats the reason you can either do

import ReactDOM from 'react-dom';

and then use

ReactDOM.render()

or use it like mentioned in your question.

查看更多
登录 后发表回答