nodejs require inside TypeScript file

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

I am wondering how to load regular nodejs module from node_modules directory from inside TypeScript class.

When I try to compile .ts file that contains:

var sampleModule = require('modulename'); 

compiler tells me I cannot use require in this scope. (that line is at the beginning of the file).

Is there a way how to load and use modules from node_modules inside TypeScript class?

回答1:

Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window, document and such specified in a file called lib.d.ts. If I do a grep for require in this file I can find no definition of a function require. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare syntax:

declare function require(name:string); var sampleModule = require('modulename'); 

On my system, this compiles just fine.



回答2:

The correct syntax is:

import sampleModule = require('modulename'); 

or

import * as sampleModule from 'modulename'; 

Then compile your TypeScript with --module commonjs.

If the package doesn't come with an index.d.ts file and it's package.json doesn't have a "typings" property, tsc will bark that it doesn't know what 'modulename' refers to. For this purpose you need to find a .d.ts file for it on http://definitelytyped.org/, or write one yourself.

If you are writing code for Node.js you will also want the node.d.ts file from http://definitelytyped.org/.



回答3:

The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require(). This was previously done using packages like typings, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:

npm install --save-dev @types/node 

Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.



回答4:

Use typings to access node functions from TypeScript:

typings install env~node --global 

If you don't have typings ? install it:

npm install typings --global 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!