5

How can I import Node modules which reside in the node_modules folder in TypeScript?

I get an error message (The name ''async'' does not exist in the current scope) when I try to compile the following piece of TypeScript code:

// Converted from: var async = require('async');
import async = module('async');

3 Answers 3

1

You need to create a definition file and include this:

module "async" {}

then add a reference to this definition file in your TypeScript code

///<reference path='definition-file.d.ts' />

import async = module('async');
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. The <reference /> tag is not required though.
You would want to put it in a separate file (by convention it should be called async.d.ts) and then you would need to reference it. The extra reason to keep it in the separate file is that you probably want to declare the exports of that async, such as functions, global variables and classes declared there.
This worked for me, but then I get compile errors because the empty module definition doesn't have the exported methods from the actual npm module. I have a d.ts file for the module but can't figure out how to wire up it's definition to my module shim.
This solution is for an old version of typescript and no longer works.
This isn't the right way to use import as you are not importing any types. The only thing this gives you over just using var x = require('x') is that the compiler can control whether it is an AMD or CommonJS module. This is probably not what you want.
1

The standard "import blah = require('x')" semantics in typescript flat out don't work with node modules.

The easiest way to work around this is to define and interface and use require explicitly, rather than import:

// You can put this in an external blah.d file if you like; 
// remember, interfaces do not emit any code when compiled.
interface qOrm {
    blah:any;
}

declare var require:any;
var qOrm:qOrm = require("../node_modules/q-orm/lib/q-orm");

var x = qOrm.blah;

Comments

1
npm install --save-dev @types/async
npm install --save async

And the syntax:

import * as async from "async"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.