In TypeScript with Express/Node.js, you might encounter different syntax for importing modules. The TypeScript Handbook shows:
import express = require(‘express’);
However, the typescript.d.ts file uses:
import * as express from “express”;
Which syntax is more correct as of early 2016? What are the differences between typescript require vs import approaches, if any? Additionally, where can you find the best source for the latest syntax updates on this topic?
Hey Anjuyadav,
These two import styles in TypeScript serve similar purposes but have some differences:
import * as creates an identifier that represents a module object, which can only have properties and cannot be called or instantiated. This is consistent with the ES6 specification, where module objects are not callable or newable. For example:
import * as express from ‘express’;
If you attempt to call express() after this import, it will be illegal according to the ES6 spec.
import express = require(‘express’); is a TypeScript-specific syntax that allows importing modules in a way that maintains compatibility with CommonJS-style modules. This style is suitable for modules that export a function or class and is often used with Node.js modules.
import express = require(‘express’);
Alternatively, with recent versions of TypeScript and module loaders that support ES6 modules, you might use:
import express from ‘express’;
This approach aligns with ES6 module syntax, and express here can be a callable function or constructor.
Hey AnjuYadav,
Namespace Import (ESM-compatible):
If you’re using an environment that supports ES6 modules and you need to import a module with a default export, you can use a namespace import and then access the default export. This can be useful when working with modules that have both default and named exports.
import * as myModule from ‘my-module’;
const result = myModule.default();