JavaScript模块:export和import语法详解 - 简书
学习了链接中的内容,感觉不错。写了个小实验,入坑几次。 因为有安全问题,所以使用import后,仍然需要跑在apache上运行例子。
1. info.js
export default function sayHi(){
alert("sayHello!");
}
export var limitedNum=123;
export var person={
fname: "San",
lname:"zhang",
phone: "156408",
address:"GanJingZi District",
getFullName: function(){
return this.fname+" "+ this.lname;
}
}
function play( name ) {
alert("I like playing with "+ name);
}
function travel( name) {
alert("I like traveling with "+name);
}
export {play, travel};
export {play as swim, travel as drive};
2. imp.js
import {person} from "./info.js";
import sayHi from "./info.js";
alert(person.getFullName());
sayHi();
3. index.html
<!DOCTYPE html>
<html>
<head>
<title>index</title>
</head>
<body>
<h1>in folder sdmhttp</h1>
<p>This is test for import</p>
</body>
<script type="module" src="imp.js"></script>
<script type="module">
import {play, travel} from "./info.js";
import {swim, drive} from "./info.js";
import {swim as dive, drive as climb} from "./info.js";
play("play: John");
swim("swim: John");
travel("travel: Jane");
drive("drive: Jane");
dive("dive: Kate");
climb("climb: Kate");
</script>
</html>
<script type="module" src="imp.js"></script>
type="module" 告诉浏览器支持模块化, 否则会提示将import放在模块最顶端错误
import {person} from "./info.js"; 不加{}, 提示getFullName不是方法的奇妙错误。