我正在使用带有AMD和require.js的Typescript,但我无法使用typescript编译器输出将在加载模块后执行的代码。
这是main.ts
:
import { foo } from './bar';
foo('world');
这是bar.ts
:
export function foo(name: string) {
alert('Hello ' + name);
}
我用以下tsconfig.json
文件编译它:
{
"compilerOptions": {
"alwaysStrict": true,
"module": "amd",
"outFile": "client.js",
"target": "es5"
},
"files": [
"main.ts"
]
}
并将其包含在我的HTML中:
<script data-main="client/client.js" src="/static/require.js"></script>
但是,生成的JavaScript代码如下所示:
define("bar", ["require", "exports"], function (require, exports) {
"use strict";
function foo(name) {
alert('Hello ' + name);
}
exports.foo = foo;
});
define("main", ["require", "exports", "bar"], function (require, exports, bar) {
"use strict";
bar.foo('world');
});
除了我想直接在main
模块中执行代码之外,一切都很好。所以最后的定义应该是
define(["require", "exports", "bar"], ...
而不是
define("main", ["require", "exports", "bar"], ...
目前,我需要用JavaScript编写的第三个脚本来加载main
模块,我认为将main
模块作为可重用代码是不好的风格。
如何让typescript编译器输出main.ts
作为可执行定义而不是模块定义?
答案 0 :(得分:0)
Function define
仅定义一个模块,无论TypeScript如何生成代码,它都不会执行该模块。
在定义了所有模块之后,您必须执行一个脚本,该脚本应包含一个调用require
方法的语句。
因此,在加载脚本后,您将拥有一个不应该采用AMD格式的脚本,它应该只包含以下语句...
require(['main'], function (main) {
// your main has been loaded !!!
});
Typescript不会生成这样的语句,因为它假定所有模块均为AMD格式。但是,调用和执行模块是AMD loader的功能,调用者应手动调用和调用该模块。
答案 1 :(得分:-2)
当您使用'import ...'时,TypeScript将编译您问题中显示的AMD模块。您是否可以尝试以下代码(也请查看本教程:http://www.codebelt.com/typescript/typescript-amd-with-requirejs-tutorial/)以验证它是否会产生您要求的输出?
Hibernate: select student0_.rollNumber as rollNumb1_3_0_, student0_.ADDR_ID as ADDR_ID4_3_0_, student0_.CLASS_TEACHER_ID as CLASS_TE5_3_0_, student0_.name as name2_3_0_, student0_.surname as surname3_3_0_, address1_.ID as ID1_0_1_, address1_.Country as Country2_0_1_, address1_.details as details3_0_1_, teacher2_.teacherId as teacherI1_4_2_, teacher2_.name as name2_4_2_, teacher2_.surname as surname3_4_2_ from Student student0_ left outer join ADDRESS address1_ on student0_.ADDR_ID=address1_.ID left outer join Teacher teacher2_ on student0_.CLASS_TEACHER_ID=teacher2_.teacherId where student0_.rollNumber=?
Hibernate: select contacts0_.STUD_ID as STUD_ID3_2_0_, contacts0_.id as id1_2_0_, contacts0_.id as id1_2_1_, contacts0_.number as number2_2_1_, contacts0_.stud_id as stud_id3_2_1_, contacts0_.type as type4_2_1_ from Phone contacts0_ where contacts0_.STUD_ID=?
Hibernate: call next value for hibernate_sequence
Hibernate: call next value for hibernate_sequence
Hibernate: insert into Phone (number, stud_id, type, id) values (?, ?, ?, ?)
Hibernate: insert into Phone (number, stud_id, type, id) values (?, ?, ?, ?)
Hibernate: update Phone set STUD_ID=null where STUD_ID=? and id=?
Hibernate: update Phone set STUD_ID=null where STUD_ID=? and id=?
Hibernate: update Phone set STUD_ID=? where id=?
Hibernate: update Phone set STUD_ID=? where id=?
Hibernate: delete from Phone where id=?
Hibernate: delete from Phone where id=?