Lazy Loading Module
In this lesson, you will see how to lazy load a module.
TypeScript analyzes the code while transpiling into JavaScript and can detect if an import is being used only for its type or not. Removing code is an important notion which helps to remove the size of the bundle of dependencies. It is also important if you want to lazy load a module. Lazy loading is the principle of loading on-demand when the module is required. Lazy loading gives a performance boost by initially only loading what is needed. Hereafter, the lazy loading pattern can load additional modules for a particular route or for particular actions. The support for lazy loading is still in an infantile stage with a syntax that requires being closer to a specific module target.
For example, a way to do this with TypeScript is to import using require
. Inside the function that uses the lazily loaded module, the code calls require
and requires you to create an element of the module and mark its type with typeof
, with the imported type at the top of the file. This line of code must set the value by calling require again. The code below was for TypeScript prior to version 2.4:
Get hands-on with 1200+ tech skills courses.