Why is Strict DI mode good for AngularJS app?

Angular framework offers Dependency Injection (DI) feature out of the box that can be used when defining components such as services, directives, filters, animations or when providing run and config blocks for a module. In this post, I’ll tell you why is strict DI mode good for AngularJS app.

If you define the dependencies without using an array of string in your angular app, then you are doing it wrong. This way of registering the dependencies will work well for non minified version of the JavaScript source file.

But if you intend to minify the files for production, which everyone must, then all those (dependency) arguments will be changed to something really random which angular will not be able to map to any registered component. So ultimately, an error will be thrown by the framework.

To avoid this mistake, one can just make sure to always use an array of type string to instruct the dependencies. Read this in more detail. If you are your own then you can maybe keep this tip in mind. However, if working in a team, it is good to configure this using the options below so that everyone in the team follows this. If not, then they will encounter an error.

How to enable strict mode?

This mode can be enabled using two options as mentioned below.

The first option is:

The second options is:

I like to use the JavaScript option as it’s configured in the module’s bootstrap call. It’s a personal preference but make sure to enable this mode for development (maybe) & production (definitely).

Does Strict DI mode add any performance benefits?

As this mode forces you to make sure that your injectable functions are explicitly annotated, it improves angular’s performance when injecting dependencies in your injectable functions because it doesn’t have to dynamically discover a function’s dependencies.

How to automate the explicit annotation?

Explicit annotations for the dependencies can also be automated via a tool like ng-annotate for production use and when this mode is enabled.

By following any of the two options above, you can be rest assured that angular framework will be smart enough to inject the correct dependencies for non and minified version of your application.

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger