简体   繁体   中英

Importing Node modules in TypeScript

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');

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');

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;
npm install --save-dev @types/async
npm install --save async

And the syntax:

import * as async from "async"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM