Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does lazy module loading work in typescript?

In this typescript book section the author explains lazy loading with the following example:

import foo = require('foo');

export function loadFoo() {
    // This is lazy loading `foo` and using the original module *only* as a type annotation
    var _foo: typeof foo = require('foo');
    // Now use `_foo` as a variable instead of `foo`.
}

According to the author typescript only loads the type of foo on the first call to require but on the second call when a foo var is created it loads the entire module required to create the var _foo.

How does this work. Can someone show a more detailed example of what's going on under the hood?

like image 752
Ole Avatar asked Dec 19 '22 08:12

Ole


1 Answers

It's mentioned in the typescript handbook

The compiler detects whether each module is used in the emitted JavaScript. If a module identifier is only ever used as part of a type annotations and never as an expression, then no require call is emitted for that module.

In this example, the first foo (the one without an underscore) is used only once in the type annotation as an argument of typeof, so the first require('foo') is omitted from the generated javascript code. You can check generated .js file to see that, and there would be only one call to the require at runtine, the 'second' one.

When loadFoo() is called, require('foo') is executed, calling built-in node.js require() function which loads foo module at runtime in the usual way.

like image 125
artem Avatar answered Dec 29 '22 15:12

artem