3

I'm just starting out using TypeScript with Angular. I am looking through some sample applications, and sometimes I see a .js that starts with an IIFE, while other times the file starts with a module declaration.

Can anyone explain when one of these should be used over the other?

1
  • I don't think you should use TypeScript modules with Angular. Angular has a module system already built in; and all registered dependencies can be inject at runtime. If you use TypeScript modules, you'll have semantic duplication, more complexity and global state, and entities which can't even be injected into your Angular app. I don't see the point of doing that. Commented Jan 27, 2016 at 5:38

1 Answer 1

4

When you write a module in TypeScript:

module MyModule {
    export class Example {

    }
}

The result is an immediately invoked function expression:

var MyModule;
(function (MyModule) {
    var Example = (function () {
        function Example() {
        }
        return Example;
    })();
    MyModule.Example = Example;
})(MyModule || (MyModule = {}));

So you can use modules in TypeScript to make your code less noisy.

Sign up to request clarification or add additional context in comments.

3 Comments

so is the convention to use modules always? If the two are interchangeable, I would expect that one should be chosen and utilized throughout an application.
I would prefer to use modules. In some cases, people may have upgraded some JavaScript code (which you can just paste into a .ts file) so they might not have updated them when they pulled the IIFEs in.
Why are you layering your own modules on top of Angular? What benefit do you get from this extra layer of complexity, additional global state, and semantic duplication?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.