What is the TypeScript 2.0 / ES2015 way to import assert from Node.js?

Burt_Harris picture Burt_Harris · Oct 5, 2016 · Viewed 11.7k times · Source

I'm running TypeScript 2.0.3, configured to with "target": "es2015",. I started with

/// <reference path="../../node_modules/@types/node/index.d.ts" />
import assert = require('assert');

But in Visual Studio, that gets flagged with a tooltip saying Import with 'require' cannot be used when targeting ECMAScript 6 or higher. I then tried:

/// <reference path="../../node_modules/@types/node/index.d.ts" />
import {assert} from 'assert';

Which generates Error TS2305 Module '"assert"' has no exported member 'assert'.

I've also tried:

/// <reference path="../../node_modules/@types/node/index.d.ts" />
import assert from 'assert';

Which generates Error TS1192 Module '"assert"' has no default export.

Answer

artem picture artem · Oct 5, 2016

For Node 10 and above, it's better to use strict assert which can be imported as named import and renamed for convenience as assert:

import { strict as assert } from 'assert';

assert.ok(true);

assert(true);

strict is a named export from built-in assert module. Named exports avoid many of the problems mentioned in the question, problems that come from using single module.exports CommonJS export and importing it as default import. In TypeScript 2.7, --esmoduleinterop option was added to help with that.

The rest is an old answer, written in 2016:

import * as assert from 'assert';

assert.ok(true);

assert(true);

If you run typescript from the same directory where node_modules is, you don't even need to add /// <reference ...

As @Ryan Cavanaugh noted in the comment, this syntax prompts an assumption that it will work in an environment where ES6 modules are natively supported (no such environment exist yet). It is not true, it's not possible to have ES6 module that can be used as both a namespace and a function, so I think this syntax still matches the reality better:

import assert = require('assert');

but you have to use typescript options

 --target es6 --module commonjs

to get rid of Import with 'require' cannot be used when targeting ECMAScript 6 or higher error. You can also use just --target es5 option alone if that's what you need.