javaScript-模块化开发

开发一个模块管理引擎

注意,模块仅在开始时定义一次
后续所有的使用都是使用最初实例化的模块(这也正是我们所需要的)

  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);
    });
  });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值