Javascript 无法使用TypeScript和Require.JS引用对象
我有一个打字脚本项目。基本上我有一个名为Javascript 无法使用TypeScript和Require.JS引用对象,javascript,typescript,requirejs,amd,Javascript,Typescript,Requirejs,Amd,我有一个打字脚本项目。基本上我有一个名为myId.ts的文件: export module MyModule { export class MyId { constructor() { ... } public compareTo(other: MyId): number { ... } public toString(): string { ... } } } 我有一个tsconfig.json: { "compiler
myId.ts
的文件:
export module MyModule {
export class MyId {
constructor() { ... }
public compareTo(other: MyId): number { ... }
public toString(): string { ... }
}
}
我有一个tsconfig.json
:
{
"compilerOptions": {
"target": "es5",
"noImplicitAny": true,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": false,
"module": "amd",
"outDir": "./out"
},
"files": [
"myId.ts"
]
}
我用这个命令编译这个东西:
tsc --project .
其中当前目录包含配置文件ad,也包含源文件
好吧,当编译一切正常时,我得到了out/myId.js
:
define(["require", "exports"], function (require, exports) {
var MyModule;
(function (MyModule) {
var MyId = (function () {
function MyId() { ... }
MyId.prototype.compareTo = function (other) { ... };
MyId.prototype.toString = function () { ... };
})();
MyModule.MyId = MyId;
})(MyModule = exports.MyModule || (exports.MyModule = {}));
});
引用MyId时出现问题
好的,我想在网页中使用它,并通过使用JavaScript调用它,因此通过以下方式,我创建了我的网页:
<html>
<head>
<meta charset="UTF-8">
<title>EVT Example - Minimal</title>
<script src="./require.js" type="text/javascript" data-main="./myId"></script>
</head>
<body></body>
</html>
EVT示例-最小值
但是,当我打开inspector(F12工具)并尝试引用MyModule.MyId
时,什么也找不到!如何引用我的类型
一切都很好
检查员告诉我,myId.js
实际上已经成功加载。因此,Require.JS没有加载脚本并不是一个问题
怎么办
当我打开inspector(F12工具)并尝试引用MyModule.MyId时,什么也找不到!如何引用我的类型
模块不是全局的,这是一件好事。因此,如果您键入MyModule.MyId
什么也不会发生
如果您想在控制台上访问它,可以将其放在窗口上,例如:
然后您可以在控制台中执行
MyModule.MyId
。当然,只有一个全局空间,开始污染它是一个可怕的想法(破坏了模块化可维护JavaScript的目的)。它可以做测试,我明白了。。。那很好。但是我有一个问题。。。require.js把所有东西放在哪里?如果不在窗口对象中,则在由define
调用包装的函数中的何处。顶级define
由data main调用isas
在TypeScript中允许吗?as
用于类型断言。看见
export module MyModule {
export class MyId {
constructor() { ... }
public compareTo(other: MyId): number { ... }
public toString(): string { ... }
}
}
(window as any).MyModule = MyModule;