2

I have had it suggested that:

import xxx = require('package');

is better than:

const xxx = require('package');  

and keeps all the type definitions. Is this true? It seems that the first syntax may be better, but I remain confused when import and require are used together like this.

JoelParke
  • 2,676
  • 2
  • 24
  • 38
  • Where did you see that syntax? It's nowhere to be found on the [MDN docs for `import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import). – Jack Bashford Apr 28 '19 at 04:37
  • perhaps it's a typescript thing @JackBashford - with the phrase `type definitions` (probably not though) - https://www.typescriptlang.org/docs/handbook/modules.html has no example with `import x = require('y')` – Jaromanda X Apr 28 '19 at 04:41
  • Yes, it is Typescript syntax, see https://stackoverflow.com/questions/29596714/new-es6-syntax-for-importing-commonjs-amd-modules-i-e-import-foo-require maybe – CertainPerformance Apr 28 '19 at 04:42
  • ahh, it's OLD syntax – Jaromanda X Apr 28 '19 at 04:45
  • 1
    *"When exporting a module using `export =`, TypeScript-specific `import module = require("module")` must be used to import the module."* (https://www.typescriptlang.org/docs/handbook/modules.html) – Gerardo Furtado Apr 28 '19 at 04:46

1 Answers1

2

import xxx = require('package'); is the old typescript syntax for importing modules, it is recommended you switch to the new ES standard import syntax. This might not always be possible if the module does not support it:

Both CommonJS and AMD generally have the concept of an exports object which contains all exports from a module.

They also support replacing the exports object with a custom single object. Default exports are meant to act as a replacement for this behavior; however, the two are incompatible. TypeScript supports export = to model the traditional CommonJS and AMD workflow.

When exporting a module using export =, TypeScript-specific import module = require("module") must be used to import the module

If you are deciding between import xxx = require('package') and const xxx = require('package'), I would definitely use the import version.

The importversion triggers the typescript machinery to resolve the module and to correctly type the import variable (taking advantage of any module definitions you have for that module).

The const version is just a function call to a function defined in the node definitions:

declare var require: NodeRequire;
interface NodeRequire extends NodeRequireFunction { /*...*/ }

interface NodeRequireFunction {
    (id: string): any; // just returns any.
}

As you can see this function returns any for any given module name, so in effect the variable holding the imports will be of type any and thus you will not benefit from any types you might have installed for the module.

Community
  • 1
  • 1
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357