js如何兼容多种模块规范

要写一个第三方系统对接插件
vue、react、jquery等等
怎样才能一个js兼容不同的引入方式
require
import
script src
目前代码是这样的

;(function (_params) {
  "use strict"
  var open = function(){
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    ...
  }
  
  if (typeof module !== 'undefined' && typeof exports ==='object') { 
    module.exports = open;  
  } else if (typeof define === 'function' && define.amd) { 
    define(function() {    return open;  });   
  } else {
    window.openPage = open;    
  }
})()

然后现在在vue项目中试发现依旧会执行window.openPage = open,没办法使用import、require
求助!

阅读 3.1k
1 个回答

建议使用 Webpack 来做这种事儿。

如果真要徒手写的话,可以这样:

(function moduleDefinition(root, factory) {
    const $ = 'myModule'; // 自定义模块名

    if ('object' === typeof wx && 'object' === typeof module && !!wx.login) {
        module.exports[$] = factory(); // 兼容 Wechat Mini-Program
    } else if ('object' === typeof my && 'object' === typeof module && !!my.login) {
        module.exports[$] = factory(); // 兼容 Alipay Mini-Program
    } else if ('object' === typeof swan && 'object' === typeof module && !!swan.login) {
        module.exports[$] = factory(); // 兼容 Baidu Smart-Program
    } else if ('object' === typeof tt && 'object' === typeof module && !!tt.login) {
        module.exports[$] = factory(); // 兼容 Toutiao Mini-App
    } else if ('object' === typeof exports && 'object' === typeof module) {
        module.exports[$] = factory(); // 兼容 CommonJS
    } else if ('function' === typeof define && (define.amd || define.cmd)) {
        define(factory); // 兼容 AMD/CMD
    } else if ('object' === typeof exports) {
        exports[$] = factory();
    } else if (root) {
        root[$] = factory();
    }
})(this, (() => {
    'use strict';
    
    return function() {
        console.log('hello world');
    }; // 要导出的模块示例
}));

使用时:

// 使用 import
import { myModule } from 'sample.js';
myModule();

// 使用 require
const sample = require('sample.js');
sample.myModule();

// 浏览器环境 src 直接引用
<script src="sample.js"></script>
<script>window.myModule();</script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题