What is the TypeScript 2.0 / ES2015 way to import assert from Node.js?
First, install TypeScript
definitions for Node.js
as dev dependencies
npm i -D @types/node
Then, you can import the assert
module :-)
import * as assert from 'assert';
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.