注意,模块仅在开始时定义一次
后续所有的使用都是使用最初实例化的模块(这也正是我们所需要的)
let module = (function () { const moduleList = {}; function define(name, modules, action) { modules.map((m, i) => { modules[i] = moduleList[m]; }); moduleList[name] = action.apply(null, modules); } return { define }; })(); module.define("a", [], function () { return { site: "后盾人", url: "houdunren.com" }; }); module.define("b", ["a"], function (a) { a.site = "hdcms"; }); module.define("c", ["a"], function (a) { console.log(a); });
导出:
class Lesson { data = []; init() { this.data = [{ name: "js" }, { name: "vue.js" }]; } get() { return this.data; } } let obj = new Lesson(); obj.init(); export { obj };
引入:
import { title, url, show } from "./ss.js";
注意:在html中使用模块要标记module属性
<script type="module"> import { title, url, show } from "./hd.js"; show(); </script>
使用模块后 模块内的代码会被延迟加载
所有模块化操作都为严格模式
模块只会解析一次(使得需要的模块不会重复获取浪费时间)
一定要给个名字,无论是函数还是变量
语法:
导入
import { site, show, User } from "./ss/m7.js";
导出:
function show() { return "show function"; } class User { static render() { return "user static render"; } } export { site, show, User };
建议不要这么做用什么直接导入:
import { site } from "./modules/m8.js"; console.log(site);
导入:
import * as api from "./modules/m8.js"; console.log(api.site); console.log(api.show()); console.log(api.User.render());
导出:
let site = "sss"; function show() { return "show function"; } class User { static render() { return "user static render"; } } export { site, show, User };
导入:
import ss from "./modules/ss.js";
导出:
export default class User { static render() { return "user static render"; } } // export { User as default };
导入:(导入全部用default使用)
import ss, { site } from "./modules/ss.js"; // import * as api from "./modules/ss.js"; console.log(api.default.render()); console.log(api.site);
导出:
let site = "ss"; class User { static render() { return "user static render"; } } export { User as default, site };
导入名字一般都用问价夹名称
导入规则:
import * as m131 from "./m13.1.js"; import * as m132 from "./m13.2.js"; export { m131, m132 };
如下即可实现按需加载
document.querySelector("button").addEventListener("click", () => { import("./modules/m14.js").then(({ site, url }) => { console.log(site, url); }); });