简体   繁体   English

在TypeScript中导入节点模块

[英]Importing Node modules in TypeScript

How can I import Node modules which reside in the node_modules folder in TypeScript? 如何导入位于TypeScript中node_modules文件夹中的Node模块?

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: 当我尝试编译以下的TypeScript代码时,我收到一条错误消息( 当前作用域中不存在名称''async'' ):

// 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 然后在TypeScript代码中添加对此定义文件的引用

///<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. 打字稿中的标准“import blah = require('x')”语义不适用于节点模块。

The easiest way to work around this is to define and interface and use require explicitly, rather than import: 解决此问题的最简单方法是明确定义和接口并使用require,而不是导入:

// 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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