Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript with AMD and require.js

I am using Typescript with AMD and require.js, but I cannot get the typescript compiler to output code which will be executed after loading the modules.

This is main.ts:

import { foo } from './bar';

foo('world');

This is bar.ts:

export function foo(name: string) {
  alert('Hello ' + name);
}

I compile this with the following tsconfig.json file:

{
    "compilerOptions": {
        "alwaysStrict": true,
        "module": "amd",
        "outFile": "client.js",
        "target": "es5"
    },
    "files": [
        "main.ts"
    ]
}

And include it in my HTML like this:

<script data-main="client/client.js" src="/static/require.js"></script>

However, the generated JavaScript code looks like this:

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');
});

Everything is fine, except from the fact that I would like to execute the code within the main module directly. So the last definition should be

define(["require", "exports", "bar"], ...

instead of

define("main", ["require", "exports", "bar"], ...

Currently, I would need a third script written in JavaScript just to load the main module, and I consider it bad style to have the main module as reusable code.

How can I get the typescript compiler to output main.ts as an executable definition instead of a module definition?

like image 674
just.me Avatar asked Jan 27 '17 11:01

just.me


1 Answers

Function define only defines a module, it will never execute the module irrespective of how code is generated by TypeScript.

After all modules have been defined, you have to execute a script, which should contain a statement calling require method.

So after your script has been loaded, you have have a script which should not be in AMD format, it should simply contain following statement...

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

Typescript will not generate such statement as it assumes all modules are in AMD format. However invoking and executing module is function of AMD loader, and caller should manually call and invoke the module.

like image 181
Akash Kava Avatar answered Oct 16 '22 19:10

Akash Kava