欢迎访问Ningto's博客

Menu
  • 首页
  • 归档
  • 关于
  • 书签
  • 必应壁纸
  • IT聚合
  • 工具
    • 我的工具列表
    • 我的网盘
    • 必应每日壁纸API
    • Html转Markdown
    • 仙尘光标
Menu

js库支持CommonJs和浏览器的标准写法

最后更新 2017-08-01 13:30:07   阅读量 2323

Table of Contents

  • 1. 浏览器端测试
  • 2. nodejs端测试

现在github上的很多开源js库都同时支持CommonJs和浏览器,简单的介绍一下写法。

如有两个库A.js和B.js,B.js引用了A.js,如果我们要使用B.js库,那应该怎么写呢?

A.js源码

(function(global, factory) {

    /* CommonJS */ if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
        module['exports'] = (function() {
            return factory();
        })();
    /* Global */ else
        global["A"] = factory();

})(this, function() {
    "use strict";
    return {
      sum: function(x, y) {
        return x + y;
      }
    }
});

B.js源码

(function(global, factory) {
    /* CommonJS */ if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
        module['exports'] = (function() {
            var A; try { A = require("./A"); } catch (e) {}
            return factory(A);
        })();
    /* Global */ else
        global["B"] = factory(global["A"]);

})(this, function(A) {
    "use strict";
    return {
      output: function(x, y) {
        var result = A.sum(x, y);
        console.log(result);
      }
    }
});

从上面代码可以看出B.js使用A.js的方法,统一从参数传进去。如果A.js模块是通过npm安装在node_modules里面,B.js引入的时候就不用写相对路径了,直接 A = require("A")

浏览器端测试

index.html中使用,直接把index.html拖到浏览器中,通过开发者工具的Console可以看到输出日志

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="root"></div>
  <script src="./A.js"></script>
  <script src="./B.js"></script>
  <script>
    B.output(3, 4)
  </script>
</body>
</html>

nodejs端测试

index.js中使用,打印输入7

var B = require('./B')
B.output(3, 4);
(转载本站文章请注明作者和出处:泞途 - ningto.com)

下一篇 – react判断滚动到底部以及保持原来的滚动位置
上一篇 – fetch跨域post,后端express

  1. Javascript

toningto@outlook.com

推荐文章

beast websocket demo

降权启动应用

标签云

Others Qt Go Web Product Javascript Mobile Linux Database Node.js Tools Design MQ Java Shell Bug Android Mac MongoDB Python C/C++ Tips Windows Life React Boost IOS

推广链接

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

多谢支持,用了好几年,服务很稳定支持多设备!

其他

文章RSS

Copyright © 2016 Welcome To Ningto Blog | 鄂ICP备17003086号-2