我使用SystemJS作为一个模块系统来编译我的TypeScript文件,但是每当我在浏览器中(通过活服务器)加载页面时,我都会得到以下错误:
ReferenceError: Sensor is not defined
at (index):17
at <anonymous>这是我的index.html文件:
<!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>Sensor</title>
</head>
<body>
<input type="text" id="textField"/>
<p id="text"></p>
<script src="node_modules/systemjs/dist/system.js"></script>
<script>
SystemJS.import('dist/index.js').then( function() {
var textField = new Sensor(document.getElementById('textField')).setName('textField');
}).catch(function(err) { console.log(err); });
</script>
</body>
</html>这是我的tsconfig.json文件:
{
"compileOnSave": true,
"compilerOptions": {
"module": "system",
"target": "es5",
"outFile": "dist/index.js"
},
"files": [
"./src/sensor.ts",
"./src/signal.ts",
"./src/signal_receiver.ts"
]
}我检查了输出文件,看起来Sensor 是定义的:
System.register("sensor", ["signal", "signal_receiver"], function (exports_3, context_3) {
...
exports_3("Sensor", Sensor);编辑:我现在检查了,当我试图调用它们时,没有定义任何函数。
发布于 2017-12-01 23:26:25
我看到你的代码有两个问题。一个是您正在使用一个包,但是您的代码忽略了这一点。第二,您不是从模块中获取Sensor类,而是从全局空间获得它。
在tsc生成的代码中,对System.register的调用具有第一个参数的"sensor",这意味着您正在处理一个包。这种调用硬编码模块名,这里的模块名是"sensor"。SystemJS捆绑包可以用script元素加载,因此您可以在加载SystemJS之后添加该包:
<script src="dist/index.js"></script>这将加载整个包并使其中的所有模块都可供使用。
然后,为模块生成的代码将Sensor类导出为模块上的Sensor字段。(这就是exports_3("Sensor", Sensor)代码所做的。)所以当你使用它的时候,你需要从模块中得到它。因此,守则应该是:
SystemJS.import('sensor').then(function(sensor) {
var textField = new sensor.Sensor(document.getElementById('textField')).setName('textField');
}).catch(function(err) { console.log(err); });在这段代码中,我要求SystemJS加载名为"sensor"的模块(与System.register使用的名称相同),并将sensor添加到传递给.then的回调的参数列表中,并将类称为sensor.Sensor。
https://stackoverflow.com/questions/47602125
复制相似问题