为什么我需要'默认'在模块导出?

时间:2017-09-28 12:34:56

标签: webpack module

我正在使用ES6语法导出一些模块并将它们与webpack捆绑在一起。 但这只适用于我添加default关键字的情况。这是做什么的?

为什么我不能使用export class Person? Webpack抱怨它需要default类。

export class Person       // doesn't work
export default class {    // works
    constructor (id) {
        this.name = id
    }
    logname () {
        console.log("Person: " + this.name)
    }
}

应用

import Person from "./person.js";

export class App {
    constructor () {
        const p = new Person("Slim Willy Joe")
        p.logname()
    }
}

1 个答案:

答案 0 :(得分:2)

如果您正在使用此

export class Example

然后你的导入应该是这样的

import { Example } from 'your-file';

如果要重命名课程(示例 - > MyClass),则需要

import { Example as MyClass } from 'your-file'

但如果您使用默认代码,则代码将如下所示

// example.js
export default class Example

// your-another-file
import MyClass from 'example';

有时我们需要命名导出,默认不是一个好的解决方案