使用AMD和require.js的TypeScript

19

我正在使用Typescript与AMD和require.js,但是我无法让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 输出为可执行定义而不是模块定义?

2个回答

2

函数定义仅定义模块,无论TypeScript如何生成代码,它都不会执行模块。

在所有模块都被定义之后,您必须执行一个脚本,其中应包含调用require方法的语句。

因此,在加载脚本后,您将拥有一个不应该是AMD格式的脚本,它应该只包含以下语句...

require(['main'], function (main) {
   // your main has been loaded !!!
});

Typescript不会生成这样的语句,因为它假设所有模块都是以AMD格式。然而,调用和执行模块是AMD加载器的功能,调用者应该手动调用和执行模块。

-4

当您使用“import…”时,TypeScript 将编译 AMD 模块,就像在您的问题中显示的那样。 您可以尝试以下代码(同时检查此教程)以验证它是否会产生您所要求的输出?

/// <reference path="[YOUR IMPORT FILE]" />
/// ...

/**
 * Main entry point for RequireJS
 */
require(
    [
        // YOUR IMPORT DEFINITIONS
    ],
    (/* YOUR IMPORT VARIABLES */) => {
        'use strict';

        // YOUR CODE HERE
    }
);

1
不要在模块中使用 /// <reference path="[YOUR IMPORT FILE]" />,而是直接使用 import - Aluan Haddad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接