How do I load a regular NodeJS module (from
node_modules) from within a
When I try to compile
.ts file that contains:
var sampleModule = require('modulename');
Compiler prompts that I can't use require in this scope. (that line is at the beginning of the file).
Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for
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 function require(name:string); var sampleModule = require('modulename');
On my system, this compiles just fine.
The correct syntax is:
import sampleModule = require('modulename');
import * as sampleModule from 'modulename';
Then compile your TypeScript with
If the package doesn't come with an
index.d.ts file and its
package.json doesn't have a
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/.