Skip to content
Advertisement

Typescript – Conditional require

One of the problems of moment-timezone is that it gives you a warning if you include it multiple times. I have a module that requires the timezone. Because I don’t know if whoever is using will or will not set the timezone themself, I have the following:

if (moment.tz === undefined) {
    require('moment-timezone');
    moment.tz.setDefault('America/Los_Angeles');
}

This works fine in normal Javascript. I recently was experimenting to switch to Typscript, and when I do this, I get the error that Cannot find name 'require'.

I switched that line to import momentTimezone = require('moment-timezone'); but then get An import declaration can only be used in a namespace or module.

What can I do?

Advertisement

Answer

The import foo = require ('foo') is typescript specific. It does two things , import the type definitions to the declaration space and the actual module to the variable space. If you don’t use the imported module at any point and only use it for typings then it will be removed at runtime . But if you use it on the variable namespace, e.g., calling a method or assigning it to a variable then you will get a runtime import . Knowing this is very important because it will save you surprised .

If you want to import and use the type definitions and only import the actual module if some condition is met, then you have to combine typescript’s import with the regular require like this:

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`.
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement