javascript import export

本文详细解析JavaScript中export和import的语法,并通过实例演示如何在实际项目中运用。学习者需注意模块加载安全与常见错误,如导入函数和变量的正确用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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不是方法的奇妙错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值