我有一个使用function(global, factory)
的遗留代码,类似于this:
// legacy.js
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
console.log('my amd One');
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
console.log('my cjs One');
module.exports = factory();
} else {
console.log('my esm One');
global.One = factory();
}
})(this, function () {
console.log('hello One');
function One(options) {
console.log("function One", options);
var self = this;
self.connect = (url) => {
console.log('One.connect: ' + url)
}
}
One.prototype.myone = function (roomId, token) {
console.log('myone: ' + roomId + ', ' + token);
}
return One;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
console.log('my amd Two');
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
console.log('my cjs Two');
module.exports = factory();
} else {
console.log('my esm Two');
global.Two = factory();
}
})(this, function () {
console.log('hello Two');
function Two(options) {
console.log("function Two", options);
var self = this;
self.connect = (url) => {
console.log('Two.connect: ' + url)
}
}
Two.prototype.mytwo = function (roomId, token) {
console.log('mytwo: ' + roomId + ', ' + token);
};
return Two;
});
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
console.log('my amd Three');
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
console.log('my cjs Three');
module.exports = factory();
} else {
console.log('my esm Three');
global.Three = factory();
}
})(this, function () {
console.log('hello Three');
function Three(options) {
console.log("function Three", options);
var self = this;
self.connect = (url) => {
console.log('Three.connect: ' + url)
}
}
Three.prototype.mythree = function (roomId, token) {
console.log('mythree: ' + roomId + ', ' + token);
};
return Three;
});
我已经设置了webpack
与babel
,以便我可以import
所有One
,Two
,Three
,并希望使用它从ES6代码,但似乎我只能使用Three
,这是最后定义的。
我在es6.js中导入并使用它,如下所示
// es6.js
import One from './legacy'
// const legacy = require('./legacy')
// console.log(legacy)
// console.log(legacy.One)
console.log(One) // prints out Three
function initTest() {
const one = new One('hw');
console.log('one: ', one); // prints out an instance of Three
// one.myone('room1', 'token1'); // this will crash, myone is undefined but idk why??
one.mythree('room1', 'token1'); // works
}
document.addEventListener('DOMContentLoaded', () => {
initTest();
})
有人知道我应该怎么做才能正确访问One
和Two
吗?我试过使用命名的import {One, Two, Three}
或const legacy = require('./legacy');
,但没有用。
1条答案
按热度按时间ru9i0ody1#
老实说,模块坏了。
如果您将它作为CommonJS模块加载(您就是这样),那么每个IIFE都将调用如下所示的行:
因此,第一个IIFE将
One
指定为要导出的内容,然后第二个IIFE用Two
覆盖它,第三个用Three
覆盖。这些IIFE未设计在同一文件中。
将它们移到单独的文件中。