There is a mechanism for dynamic imports in TypeScript, although the implementation differs based on the module kind.
The example below (for AMD) will conditionally load the module:
declare function require(moduleNames: string[], onLoad: (...args: any[]) => void): void;
import * as ModuleAlias from './mod';
const someCondition = true;
if (someCondition) {
require(["./mod"], (module: typeof ModuleAlias) => {
console.log(module.go());
});
}
The import
statement at the top of the file is inert, and the actual loading of the module will not happen unless the condition if (someCondition)
is true.
You can test this by changing someCondition
and seeing the impact on your network tab, or you can look at the generated code... in the dynamic version, "./mod"
does not appear in the define
call. In the non dynamic one, it does.
With Dynamic Loading
define(["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const someCondition = true;
if (someCondition) {
require(["./mod"], (module) => {
console.log(module.go());
});
}
});
Without Dynamic Loading
define(["require", "exports", "./mod"], function (require, exports, ModuleAlias) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const someCondition = true;
if (someCondition) {
console.log(ModuleAlias.go());
}
});