Home >Web Front-end >JS Tutorial >Introduction to knowledge points in export and export default (with examples)

Introduction to knowledge points in export and export default (with examples)

不言
不言forward
2019-03-20 11:28:284471browse

This article brings you an introduction to the knowledge points in export and export default (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There are many articles about export and export default on the Internet. Most of them only talk about usage, but do not mention key things such as performance and packaging.
Everyone should be able to understand that import * from 'xxx' will package all the export default contents in the file into the file, while import {func} from 'xxx' will only import the func in the file, so export will inevitably Less packaged than export default. Look at the example

utils.js

const func1 = () => {
    console.log('func1');
}

const func2 = () => {
    console.log('func2');
}

export default {
    func1,
    func2
}

index.js

import { render } from "react-dom";
import common from './common';

class Index extends Component {
  render() {
    common.func1();
    return (
      123456
    );
  }
}

render(<index></index>, document.getElementById('app'));

If you use this export default method, what will the packaged file look like? Let's take a look

Introduction to knowledge points in export and export default (with examples)

We find that the entire file is packed

in another way
utils.js

const func1 = () => {
    console.log('func1');
}

const func2 = () => {
    console.log('func2');
}

export {
    func1,
    func2
}

index .js

import { render } from "react-dom";
import {func1} from './common';

class Index extends Component {
  render() {
    func1();
    return (
      123456
    );
  }
}

render(<index></index>, document.getElementById('app'));

Result:

Introduction to knowledge points in export and export default (with examples)

Only func1 is packaged

In summary, export default may indeed package more unnecessary content , but in some scenarios it is better to use export default.
So the summary is as follows:

1.当文件存放着很多方法,变量不同场景需要引用不同方法,请用export
2.当类只有某几个方法,并且每次引用都需要用到里面的大部分方法,请用export default,
  毕竟还有方法提示
3.当值导出一个方法,类请用export default
4.如果一个文件只会被某一个其他文件的子文件,不会被其他文件引用,并且其中的方法都会被用到,
  考虑用export default。比如某个业务文件夹下的action.js,用的时候用import api from './action';
  方便识别,不用重复在import的{}中添加,也可以用方法提示。
4.如果一个文件兼有以上需求 可以同时export和export default

This article has ended here. For more other exciting content, you can pay attention to the JavaScript Tutorial Video column of the PHP Chinese website!

The above is the detailed content of Introduction to knowledge points in export and export default (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete