Search code examples
javascripttypescripttypescript1.5es6-module-loaderumd

TypeScript UMD both 'module' and 'define' are undefined


I transpile my TypeScript using "-m umd" because my project includes server, client and shared code. However, client side code doesn't work in browser. The browser doesn't even display any error and the breakpoint I located didn't hit, so I had to remove js-ts mapping. Then, I was able to debug it and I found the problem.

Following is the code that UMD generates:

(function (factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(["require", "exports", "./model"], factory);
    }
})(function (require, exports) {
    //my code
});

It doesn't work because both 'module' and 'define' are undefined. Therefore my code is not executed and there isn't even any exception.

What's wrong? How could I make it work?


Solution

  • Today none of the browsers understand AMD modules natively. (In fact none of the module formats except standard ES6 in some really new builds of MS Edge).

    So you have to bundle a module loader with your code. I suggest you to either use only AMD modules and a lightweight AMD loader, concatenating your modules and the module loader in a single file, or use RollupJS, which generates a loader-less bundle from standard ES6 modules. If I remember correctly the rollup-plugin-typescript plugin doesn't work well with multiple files, so I recommend compiling typescript with tsc into es6 modules, and bundle it with rollupjs in a second step.

    You can read more about module bundlers in this StackOverflow thread: Do I need require js when I use babel?

    EDIT

    Today (September 2016) the rollup-plugin-typescript plugin works like a charm! Definitely this is the recommended way now.