150

I am using TypeScript with Express/Node.js.

For consuming modules, the TypeScript Handbook shows the following syntax:

import express = require('express');

But also the typescript.d.ts file shows:

import * as express from "express";

I also searched the MSDN blog but could not find anything.

Which one is more correct as of early 2016? What are the differences between the two, if any?

Where is the best source to find information on the latest syntax to use so I can find this information in the future?

0

2 Answers 2

203

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

6
  • 7
    “In general you should use the ES6 syntax unless you have some reason not to (I can't think of any offhand)” FWIW I gave an answer why not in this duplicate question here.
    – C Snover
    Mar 1, 2016 at 22:18
  • I'm a little confused between the apparent contradiction here. Which advice should I be following? @CSnover is your advice still just as applicable today in 2016 as it was when you posted it? Thank you. Mar 2, 2016 at 19:09
  • 1
    @AdamThompson yes, see the part “2016 update”.
    – C Snover
    Mar 2, 2016 at 19:12
  • In the source code of visual studio, I found they write import express = require('express');
    – cwtuan
    Aug 31, 2017 at 3:14
  • 3
    @Ryan Cavanaugh What does "depending on your module loader" mean? How do I find out what module loader I have? Thanks.
    – Old Geezer
    Sep 12, 2017 at 5:27
35
import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

3
  • 8
    but this means express should be an object of exports and would not make sense to be called as express()
    – Emobe
    Mar 16, 2019 at 11:51
  • 1
    @Emobe I found that to be true only if your ts.config has "esModuleInterop": true if that flag is set to false, express() seems to be valid code
    – Sam
    Aug 14, 2019 at 23:59
  • @Sam Valid but not clean. It does not make sense to use it like that.
    – Emobe
    Aug 15, 2019 at 19:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.