Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `import from` and `import require` in TypeScript

I use node.js and I recently decided to give TypeScript a shot, But I'm kinda confused on how modules get imported. I see two different syntax that I couldn't find out what's their difference exactly:

import * as a from 'a'; // ES6 standard to import stuff
// OR ...
import a = require('a');

Are these the same thing? and if they're not, where should I use each one of them?

like image 793
Rsh Avatar asked Jun 06 '16 07:06

Rsh


People also ask

What is the difference between import and require in TypeScript?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with .

Is require and import same?

Require is Non-lexical, it stays where they have put the file. Import is lexical, it gets sorted to the top of the file. It can be called at any time and place in the program. It can't be called conditionally, it always run in the beginning of the file.

Is import better than require?

The major difference between require and import , is that require will automatically scan node_modules to find modules, but import , which comes from ES6, won't. Most people use babel to compile import and export , which makes import act the same as require .

Can you use import and require together?

With modern web development, we use require or import to refer to JavaScript dependencies. And, sometimes, we use both in combination and use what works for the library.


1 Answers

import * as a from 'a'; is the new "ES6 style" import syntax (available since Typescript 1.5).

Whenever possible, this syntax should now be used.

There is one caveat though. The ES6 import syntax can only import modules (as defined by ES6) or objects (classes, interfaces, vars,... ) exported as part of a module.

Some Javascript librairies will directly export a function or class, and the corresponding definition file will typically look like this:

declare module "my-class" {

    class MyClass { ... }

    export = MyClass
} 

In this case, the "old" import syntax is the only one that can be used

import MyClass = require("my-class");

Failure to use this syntax will result in error TS2497

Check this issue for details and a possible workaround which would be, in the previous case, to add an empty module declaration to the definition file

declare module "my-class" {

    class MyClass { ... }

    module MyClass {} // <=

    export = MyClass
} 
like image 92
Bruno Grieder Avatar answered Sep 19 '22 19:09

Bruno Grieder