Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

javascript - Why to you have to specify the type of the export (let, var, const...) in ES2015?

As I'm reading here, ES2015 allows you to export var, const, let, function, class and default.

export var myVar1 = ...;
export let myVar2 = ...;
export const MY_CONST = ...;

export function myFunc() {
    ...
}
export function* myGeneratorFunc() {
    ...
}
export class MyClass {
    ...
}

But I don't understand why. In my layman opinion, there should be named exports and default exports.

The type of what you are exporting doesn't seem to matter. I mean, when you export default, do you specify the type? No you don't, and it works. Additionally, what difference can it make to export var or let? What difference can it make to export const? When you import a module it's immutable anyway (AFAIK).

So, why do you have to specify the type of the export?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't have to specify the type of the export - you have to specify the type of the local binding in your module.

there should be named exports and default exports.

There are:

export {localX as exportedX};
export {localX as default};

All those examples you've given are actually shorthands, which both declare a local variable and export it under the same name:

var myVar1 = …;
let myVar2 = …;
const MY_CONST = …;
function myFunc() {
    …
}
function* myGeneratorFunc() {
    …
}
class MyClass {
    …
}

export {
    myVar,
    myVar2,
    MY_CONST,
    myFunc,
    myGeneratorFunc,
    myClass
};

What difference can it make to export const? When you import a module it's immutable anyway.

That you cannot reassign it inside your module. The export doesn't export a value1, it exports a binding to your local variable. Imports actually aren't immutable, they are only non-writable.

// example.js
export var value; // this one would not work with `const`
export default function(x) {
    value = x;
}

// main.js
import write, {value} from 'example';
console.log(value); // undefined
write(42);
console.log(value); // 42

1: Default exports are a bit special in that regard. The export default … declaration does indeed allow you to directly export the value of an expression (or an anonymous function/function*/class declaration), but behind the scenes it actually does create a local variable in your module with the name *default*.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...