【发布时间】:2017-01-11 17:33:20
【问题描述】:
版本
npm: 3.10.9systemjs: 0.19.41typescript: 1.8.10rxjs: 5.0.3
背景
我有一个项目(用 typescript 编写),我正在尝试将 rxjs 添加到其中,但在通过 systemjs 加载捆绑文件时遇到了问题。
SystemJs 配置
System.config({
transpiler: 'typescript',
paths: {
'src:*': '/src/*',
'npm:*': '/node_modules/*'
},
map: {
'lib': 'src:lib',
'rxjs': 'npm:rxjs/bundles/Rx.js',
'typescript': 'npm:typescript/lib/typescript.js',
'systemjs': 'npm:systemjs/dist/system.src.js'
},
packages: {
lib: {
defaultExtension: 'js'
}
}
});
问题
使用上述配置,我得到以下错误。
Error: (SystemJS) undefined is not a constructor (evaluating '__extends(UnsubscriptionError, _super)')
这是由于 systemjs 错误地默认为 amd 格式而导致 Rx.js 的第 245 行的 exporter 函数永远不会被执行。
来自 systemjs 文档:
模块格式检测
未设置模块格式时,使用基于正则表达式的自动检测。这种模块格式检测永远不会完全准确,但可以很好地满足大多数用例。
尝试的解决方案
我认为在配置中将 rxjs 包格式显式设置为 global 可以解决此问题。
System.config({
transpiler: 'typescript',
paths: {
'src:*': '/src/*',
'npm:*': '/node_modules/*'
},
map: {
'lib': 'src:lib',
'rxjs': 'npm:rxjs/bundles/Rx.js',
'typescript': 'npm:typescript/lib/typescript.js',
'systemjs': 'npm:systemjs/dist/system.src.js'
},
packages: {
lib: {
defaultExtension: 'js'
},
rxjs: {
format: 'global'
}
}
});
问题 2
虽然这解决了第一个问题,但它产生了第二个问题。因为我尝试使用 rxjs 导入的所有地方现在都会引发错误,因为它们是 undefined。
import {Observable} from 'rxjs'
export class SomeClass {
...
private _isObservable(arg: any): boolean {
return arg instanceof Observable;
}
}
Uncaught TypeError: Right-hand side of 'instanceof' is not an object at SomeClass._isObservable
在控制台中调试转译的代码表明,虽然window.Rx 被正确设置为Rx 对象,但在SomeClass 上设置的rxjs_1_1 对象不是全局Rx 对象,而是另一个将Rx 全局设置为属性“Rx”的对象。
所以rxjs_1.Rx.Observable 有效,但不适用于 rxjs_1.Observable`。
(function(System, SystemJS) {System.register(['rxjs'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var rxjs_1;
var SomeClass;
return {
setters:[
function (rxjs_1_1) {
rxjs_1 = rxjs_1_1;
}],
execute: function() {
SomeClass = (function () {
function SomeClass() {
}
...
SomeClass.prototype._isObservable = function (arg) {
return arg instanceof rxjs_1.Observable;
};
return SomeClass;
}());
exports_1("SomeClass", SomeClass);
}
}
});
问题
知道我如何让它传入Rx 对象吗?
【问题讨论】:
标签: typescript systemjs rxjs5