js模块化:require、import和export

前言

  • 编写js模块必须要搞懂import和export的关系
  • Google Chrome 84.0.4147.135 (正式版本) (64 位) (cohort: Stable Installs Only)
  • 修订版本 c42bd09b3f24da1698d71d3b4f57402137163566-refs/branch-heads/4147@{#1102}
  • 操作系统 Windows 10 OS Version 2004 (Build 19041.450)
  • JavaScript V8 8.4.371.23
    注:使用命令 chrome://version/ 查看 JavaScript 版本
  • 以 es6 的标准为主

分析

  • require 为 es6 以前的模块化解决方案。这里不介绍了。
  • export 是导出模块。
  • import 是导入模块。
  • export 和 import 搭配使用。

export

export语法用于导出类、函数、对象、指定文件(或模块)的原始值。

import

import语法用于导入类、函数、对象、指定文件(或模块)的原始值。

导出、导入类

MyClass.js

class MyClass {}

MyClass.prototype.hello = function() {
	console.log("hello");
}

export { MyClass };
  • 导出名为 MyClass 的类,且 MyClass 处在导出第 1 位

jsTestMyClass.html

<script type="module">
	import { MyClass } from "./MyClass.js";

	let myClass = new MyClass();
	myClass.hello();
</script>
  • 导入名为 MyClass 的类,且 MyClass 处在导入第 1 位

另:

  • 导出的花样很多,这也是为啥要记录一下的原因。
  • 一定要记住:怎么导出的,就要怎么导入。导出和导入是搭配使用的。
  • 导出和导入的配对花样有哪些,后面慢慢补充,一篇记录不清楚,那就再来一篇。

执行效果:
在这里插入图片描述

导出、导入函数

MyFunction.js

function hello() {
	console.log("hello");
}

export { hello };
  • 导出名为 hello 的函数,且 hello 处在导出第 1 位

jsTestMyFunction.html

<script type="module">
	import { hello } from "./MyFunction.js";

	hello();
</script>
  • 导入名为 hello 的函数,且 hello 处在导入第 1 位

执行效果:
在这里插入图片描述

导出、导入对象

MyObject.js

function hello () {
	console.log("hello");
}
var obj = { hello:hello };

export { obj }; 
  • 导出名为 obj 的对象,且 obj 处在导出第 1 位

jsTestMyObject.html

<script type="module">
	import { obj } from "./MyObject.js";
	
	console.log(obj);
	obj.hello();
</script>
  • 导入名为 obj 的对象,且 obj 处在导入第 1 位

执行效果:
在这里插入图片描述

  • 从打印 obj 的结果看,obj 是个对象

导出、导入指定文件(或模块)的原始值

JsModule.js

function hello() {
	console.log("hello");
}

function run() {
	console.log("run");
}

function jump() {
	console.log("jump");
}

export { hello, run, jump };
  • 导出名为 hello 的函数,且 hello 处在导出第 1 位
  • 导出第 2 位是 run 函数
  • 导出第 3 位是 jump 函数

MyModule.js

export { hello } from "./JsModule.js";
  • 导出名为 hello 的函数,且 hello 处在导出第 1 位
  • hello 函数是从 JsModule.js 导入的

jsTestMyModule.html

<script type="module">
	import { hello } from "./MyModule.js";

	hello();
</script>
  • 导入名为 hello 的函数,且 hello 处在导入第 1 位
  • hello 函数是从 MyModule.js 导入的

执行效果:
在这里插入图片描述

为了理解简单,均使用了导入导出第 1 位的模块。

参考

https://www.cnblogs.com/libin-1/p/7127481.html
https://blog.csdn.net/youlinhuanyan/article/details/105211072

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值