Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to NodeJS require inside TypeScript file?

How do I load a regular NodeJS module (from node_modules) from within a TypeScript class?

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).

like image 213
Zdenek Sejcek Avatar asked Oct 05 '12 08:10

Zdenek Sejcek


People also ask

Can I use require with TypeScript?

TypeScript offers support for creating and using modules with a unified syntax that is similar to the ES Module syntax, while allowing the developer to output code that targets different module loaders, like Node. js (CommonJS), require. js (AMD), UMD, SystemJS, or ECMAScript 2015 native modules (ES6).

Is node js required for TypeScript?

The compiler is written in TypeScript. You need a JavaScript runtime that gives you access to the file system if you want to create files and update files, which is why you need node. js (or similar) to do a proper job. You can do everything except save files using browser script engines.

Can I use require in js file?

With require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.

For what require () is used in Node JS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.


2 Answers

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.

like image 134
Valentin Avatar answered Oct 03 '22 09:10

Valentin


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 its 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/.

like image 25
Jesse Avatar answered Oct 03 '22 11:10

Jesse