欢迎光临散文网 会员登陆 & 注册

JavaScript 中的模块如何打包运行(️三)

2023-07-23 07:21 作者:Mr蓝珲  | 我要投稿

选项 1: src 法。将 index.html 与 change.js 放在同一个目录里面。change.js 中定义了函数 changeTimeFormat()。在 index.html 要使用该函数,只需要通过 < script src="change.js"></script> 将其包含进来即可。打开 index.html, 即显示期望的结果。


index.html

change.js


选项 2: module-export-import 法。 将 index.html 与 change.js 放在同一个目录里面。  change.js 中定义了函数 changeTimeFormat(),且被导出 export function changeTimeFormat(table) { ... } 。index.html 中的 < script> 标签需要指定类型为模块, type="module"。 使用 import 语句导入 change.js 中内容,即,import * as change from './change.js' 。 用这种方法,直接打开 index.html, 不能显示期望的结果。 需要先用 static-server 运行一个本地 server, 然后在网页浏览器输入 http://localhost:9080/index.html 。 (如果使用 http-server, 则输入 http://localhost:8080/index.html)


index.html 中使用了 import 语句,来引入外部 JavaScript 代码
change.js 定义了函数 changeTimeFormat,且用 export 导出


JavaScript 中的模块如何打包运行(️三)的评论 (共 条)

分享到微博请遵守国家法律