search

Home  >  Q&A  >  body text

javascript - An understanding problem of es6 export

Dear folks, when I was watching Teacher Ruan Yifeng’s es6 introductory tutorial, there was a section that I didn’t understand even after reading it many times.

It should be noted that the export command specifies the external interface and must establish a one-to-one correspondence with the variables inside the module.

// 报错
export 1;

// 报错
var m = 1;
export m;

The above two writing methods will report errors because no external interface is provided. The first way of writing directly outputs 1, and the second way of writing directly outputs 1 through variable m. 1 is just a value, not an interface. The correct way to write it is as follows.

// 写法一
export var m = 1;

// 写法二
var m = 1;
export {m};

// 写法三
var n = 1;
export {n as m};

The above three ways of writing are correct and specify the external interface m. Other scripts can get the value 1 through this interface. Their essence is to establish a one-to-one correspondence between the interface name and the internal variables of the module.

What exactly does this "interface" refer to here?
for

// 报错
function f() {}
export f;

// 正确
export function f() {};

What is the difference?

世界只因有你世界只因有你2737 days ago582

reply all(1)I'll reply

  • 世界只因有你

    世界只因有你2017-05-19 10:24:15

    You might as well take a look directly at how the grammar is stipulated:

    export { name1, name2, …, nameN };
    export { variable1 as name1, variable2 as name2, …, nameN };
    export let name1, name2, …, nameN; // also var
    export let name1 = …, name2 = …, …, nameN; // also var, const
    
    export expression;
    export default expression;
    export default function (…) { … } // also class, function*
    export default function name1(…) { … } // also class, function*
    export { name1 as default, … };
    
    export * from …;
    export { name1, name2, …, nameN } from …;
    export { import1 as name1, import2 as name2, …, nameN } from …;

    Taken from https://developer.mozilla.org...

    The interface that

    ta is talking about is expression that is, an expression. In layman's terms, it is something that is not a constant (fixed value).

    In addition, you can use default to write like this:

    export default m = 1

    Because m = 1 是一个表达式。其它地方你可以直接 import m from ... then the value of m is 1.

    reply
    0
  • Cancelreply