nodejs需要在TypeScript文件中
我想知道如何从TypeScript类中的node_modules目录加载正规的nodejs模块。
当我尝试编译包含以下内容的.ts文件时:
var sampleModule = require('modulename');
编译器告诉我,我不能在这个范围内使用require。 (该行在文件的开头)。
有没有办法如何加载和使用TypeScript类中的node_modules模块?
当无法find符号时,Typescript将始终抱怨。 编译器为一个名为lib.d.ts的文件指定了一组window , document等默认定义。 如果我在这个文件中做一个grep for require ,我可以find一个函数require定义。 因此,我们必须自己告诉编译器,这个函数将在运行时使用declare语法存在:
declare function require(name:string); var sampleModule = require('modulename');
在我的系统上,这个编译就好了。
正确的语法是:
import sampleModule = require('modulename');
要么
import * as sampleModule from 'modulename';
然后用--module commonjs编译你的TypeScript。
如果软件包没有带有index.d.ts文件,而package.json没有"typings"属性, tsc就会吠叫,它不知道'modulename'是指什么。 为此,您需要在http://definitelytyped.org/上find.d.ts文件,或者自己写一个.d.ts文件。
如果您正在为Node.js编写代码,则还需要http://definitelytyped.org/中的;node.d.ts文件。
使用types从TypeScript访问节点函数:
typings install env~node --global
如果你没有打字😲安装:
npm install typings --global
正如迈克·张伯伦所说。 types被depricated和@types应该被使用。
npm i -D @types/node