631

I am trying to get my first TypeScript and DefinitelyTyped Node.js application up and running, and running into some errors.

I am getting the error "TS2304: Cannot find name 'require' " when I attempt to transpile a simple TypeScript Node.js page. I have read through several other occurrences of this error on Stack Overflow, and I do not think I have similar issues. I am running at the shell prompt the command:

tsc movie.server.model.ts.

The contents of this file are:

'use strict';

/// <reference path="typings/tsd.d.ts" />

/*    movie.server.model.ts - definition of movie schema */

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var foo = 'test';

The error is thrown on the var mongoose=require('mongoose') line.

The contents of the typings/tsd.d.ts file are:

/// <reference path="node/node.d.ts" />
/// <reference path="requirejs/require.d.ts" />

The .d.ts file references were placed in the appropriate folders and added to typings/tsd.d.ts by the commands:

tsd install node --save
tsd install require --save

The produced .js file seems to work fine, so I could ignore the error. But I would appreciate knowing why this error occurs and what I am doing wrong.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JerryKur
  • 7,279
  • 6
  • 24
  • 33

24 Answers24

938

Quick and Dirty

If you just have one file using require, or you're doing this for demo purposes you can define require at the top of your TypeScript file.

declare var require: any

TypeScript 2.x

If you are using TypeScript 2.x you no longer need to have Typings or Definitely Typed installed. Simply install the following package.

npm install @types/node --save-dev

The Future of Declaration Files (6/15/2016)

Tools like Typings and tsd will continue to work, and we’ll be working alongside those communities to ensure a smooth transition.

Verify or Edit your src/tsconfig.app.json so that it contains the following:

...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...

Make sure is the file in the src folder and no the one on the root app folder.

By default, any package under @types is already included in your build unless you've specified either of these options. Read more

TypeScript 1.x

Using typings (DefinitelyTyped's replacement) you can specify a definition directly from a GitHub repository.

Install typings

npm install typings -g --save-dev

Install the requireJS type definition from DefinitelyType's repo

typings install dt~node --save --global

Webpack

If you are using Webpack as your build tool you can include the Webpack types.

npm install --save-dev @types/webpack-env

Update your tsconfig.json with the following under compilerOptions:

"types": [
      "webpack-env"
    ]

This allows you to do require.ensure and other Webpack specific functions.

Angular CLI

With CLI you can follow the Webpack step above and add the "types" block to your tsconfig.app.json.

Alternatively, you could use the preinstalled node types. Keep in mind this will include additional types to your client-side code that are not really available.

"compilerOptions": {
    // other options
    "types": [
      "node"
    ]
  }
BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
cgatian
  • 22,047
  • 9
  • 56
  • 76
  • 4
    why not just "typings install --save --ambient require"? – kutomer Mar 21 '16 at 11:15
  • Excellent suggestion. I've updated the answer. I didn't know require existed. – cgatian Mar 21 '16 at 12:57
  • 1
    i get an error with this `Unable to find "require" ("npm") in the registry`. Is require part of a larger set of nodeJS typings? – dcsan Jun 12 '16 at 10:12
  • typings v1.2.0 should be: typings install dt~require --save --global – Paul J Jun 16 '16 at 08:32
  • 7
    i tihnk this is WRONG as its related to typings for requireJS, not node's built in `require`. maybe its right answer for some variation of ES5 output target but not the general case. – dcsan Aug 25 '16 at 22:07
  • I had a similar problem, and this answer may help others who want to just get going with node. also if you're using atom typescript make sure to have `"module": "commonjs", "moduleResolution": "node",` in your tsconfig. http://stackoverflow.com/a/37912109/1146785 – dcsan Aug 28 '16 at 14:19
  • @dcsan You're right. I've updated the answer to reflect using node.js instead of require. – cgatian Sep 16 '16 at 23:42
  • this isn't working for me using TS2, it doesn't seem to be picking up the @types/node definitions somehow. any ideas why? – Dave Taylor Oct 24 '16 at 10:42
  • Could be something with your TypeScript config. Try deleting the tsconfig.json and recreating with `tsc --init` just to see if it works. You can also try building the file manually (with tsc command) to see if its just the IDE thats not picking up the typings – cgatian Oct 24 '16 at 13:40
  • 2
    Please refer to jordan awnser. In my case I had install the following @types so I added -> "types": ["node","es6-promise", "core-js", "jasmine"] <- to compilerOptions in tsconfig.json – Lothre1 Oct 26 '16 at 08:22
  • @Lothre1 configuring those options is only necessary when you've specified typeRoots or types. The default tsconfig will pick these up automatically. https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types – cgatian Oct 26 '16 at 11:58
  • FINALLY got rid of the errors! I missed the step of adding the 'types' to the tsconfig. It look web storm a second to resolve everything. Thank you!! – mwilson Nov 12 '16 at 04:28
  • Hmm followed all your steps, but it says no for me. – Mathijs Segers Nov 28 '16 at 08:54
  • There's an error in your code. It's not `typeroots` but `typeRoots` with a capital `R` – RPDeshaies Feb 14 '17 at 16:14
  • No problem sir ! :) – RPDeshaies Feb 15 '17 at 13:59
  • Works here too :) – michael-mammut Mar 16 '17 at 11:23
  • For me the optional step wasn't so optional. Despite I wasn't using types before. – velop Mar 18 '17 at 10:41
  • I still does not understand why I had to write "@types/node" as a dependency when Node.js is istalled globally on my PC? Any suggestions? – Seagull Jan 15 '18 at 14:56
  • 1
    @Seagull `@types/node` are the TypeScript definitions. Node does not include these, nor should they. – cgatian Jan 15 '18 at 23:54
  • This is it `npm install @types/node --save-dev` and a restart for dumb VsCode ! – Legends Mar 16 '18 at 00:08
  • According to the documentation either types or typeRoots should be specified in the compiler options. Not both. – user5389726598465 Mar 26 '18 at 01:25
  • 1
    This answer, I tried like a fool and it caused my entire application, that at least was working, to blow up with 7 successive errors all saying the same thing... TS2304: Cannot find name 'require'. Hastily backing out... Core 2 .Net VueJs Typescript project... try at your own risk' – Clarence Jul 26 '18 at 06:40
  • @Clarence sorry the answer didn't help? – cgatian Jul 26 '18 at 22:41
  • Still getting this TS2304 error in TSC 2.9.2 even with this answers ideas. – Ben Racicot Aug 08 '18 at 12:16
  • Most likely you are editing the wrong `tsconfig.json`. – cgatian Aug 08 '18 at 23:15
  • how about solution for TS version 3, cause above is not working for angular 7 – Daniil Iaitskov Dec 21 '18 at 02:04
  • in my case for TS version 3 and angular 7 I had to put typings.d.ts into src, cause on same level with src it is ignored silently. – Daniil Iaitskov Dec 21 '18 at 03:16
  • Be warning there is 2 tsconfig one in src and one at the root – bormat Apr 19 '19 at 19:06
  • I had a similar issue, but the only things I needed to change were the target. – Urasquirrel Jul 13 '19 at 14:06
  • MAKE SURE THAT YOU --> Edit your src/tsconfig.app.json the one in SRC and not in the Root of the app folder. – Mauricio Gracia Gutierrez Oct 18 '19 at 13:21
  • 1
    TYVM, this helped me realize I forgot to update the tsconfig.app.json and the tsconfig.lib.json for my libraries and is why I was getting issues. Lead me down the path to correction! – Andrew Karstaedt Mar 23 '20 at 14:47
133

For TypeScript 2.x, there are now two steps:

  1. Install a package that defines require. For example:

    npm install @types/node --save-dev
    
  2. Tell TypeScript to include it globally in tsconfig.json:

    {
        "compilerOptions": {
            "types": ["node"]
        }
    }
    

The second step is only important if you need access to globally available functions such as require. For most packages, you should just use the import package from 'package' pattern. There's no need to include every package in the tsconfig.json types array above.

Jordan
  • 2,281
  • 1
  • 17
  • 24
  • 1
    You can either use lib for some es5 https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#including-built-in-type-declarations-with---lib Eq: "lib": [ "dom", "es5", "es2015.promise", "es2015.collection" ] – Leo Caseiro Sep 14 '16 at 00:40
  • After adding `"types": ["jasmine", "hammerjs"]` to `tsconfig.js` I hade to add `node` as well. Thanks Jordan. – Mikeumus Sep 20 '16 at 07:38
  • When I follow this advice, it breaks all of my imports. For example, `import express from "express";` is now telling me that I need to try installing @types/express or add a .d.ts file for it. – austinthemassive Oct 10 '17 at 23:25
  • 5
    If You have more `@types/...` than just `@types/node` folder don't add `"types": ["node"]` in `tsconfig.json` because TypeScript compiller will omit other not mentioned packages. This will break your IDEs types resolving. It is written here https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types – Marecky Mar 30 '18 at 07:06
  • That solution works for me in an ionic project without problems, thank you :) – Francisco Sandi May 04 '18 at 23:58
  • Would be nice if types/node was bundled in TypeScript – Codler Aug 28 '18 at 20:09
83

You can

declare var require: any

Or, for more comprehensive support, use DefinitelyTyped's require.d.ts

Also, instead of var mongoose = require('mongoose'), you could try the following

import mongoose from 'mongoose' // or
import mongoose = require('mongoose')
P Varga
  • 19,174
  • 12
  • 70
  • 108
  • 1
    Just about using `use strict` in TypeScript: [basarat answer](http://stackoverflow.com/questions/33610728/what-does-use-strict-add-for-typescript-code#answer-33619812) and [“Use Strict” needed in a TypeScript file?](http://stackoverflow.com/questions/31391760/use-strict-needed-in-a-typescript-file). It is necessary to use `use strict` in TypeScript. – Yauhen Nov 28 '15 at 19:54
  • Hm, according to that answer it's not necessary but might be beneficial to use `"use strict"`, I'll edit my answer – P Varga Dec 02 '15 at 15:58
  • using declare var require isn't fixing the real problem; just hiding it. – My Stack Overfloweth Oct 04 '16 at 19:39
  • @Ant right, keep in mind this is from 2015, and also, I'd argue there's no "problem" to fix. TypeScript 2.0 now solves this elegantly of course – P Varga Oct 05 '16 at 14:17
43

In my case, it was a super stupid problem, where the src/tsconfig.app.json was overriding the tsconfig.json setting.

So, I had this in tsconfig.json:

    "types": [
      "node"
    ]

And this one in src/tsconfig.app.json:

    "types": []

I hope someone finds this helpful, as this error was causing me gray hairs.

h22a
  • 446
  • 4
  • 3
  • 1
    This is the problem I faced. Thanks – davy Sep 11 '20 at 07:19
  • We had the same issue. This comment helps to include the "node" in the correct file; in our case, we need to adjust the tsconfig.lib.json file because it was a submodule of the main project. – Rogelio Blanco Jul 14 '21 at 17:49
14

This answer relates to modern setups (TypeScript 2.x, Webpack > 2.x)

You don't need to install @types/node (which is all of Node.js types and is irrelevant for front-end code, actually complicating things such as setTimout different return values, etc..

You do need to install @types/webpack-env

npm i -D @types/webpack-env

which gives the runtime signatures that Webpack has (including require, require.ensure, etc.)

Also make sure that your tsconfig.json file has no set 'types' array -> which will make it pickup all type definitions in your node_modules/@types folder.

If you want to restrict search of types you can set the typeRoot property to node_modules/@types.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nadav SInai
  • 490
  • 3
  • 6
  • 3
    this is important remark **also make sure that your tsconfig.json has no set 'types' array -> which will make it pickup all type definitions in your node_modules/@types folder** – Marecky Mar 30 '18 at 07:14
  • Are there any other steps needed with the webpack approach? I get a compile error ` error TS2580: Cannot find name 'require'.` – jaycer Jan 24 '19 at 21:01
10

Instead of:

'use strict';

/// <reference path="typings/tsd.d.ts" />

Try:

/// <reference path="typings/tsd.d.ts" />

'use strict';

i.e. reference path first.

Brendan Green
  • 11,676
  • 5
  • 44
  • 76
Hurricane
  • 1,454
  • 1
  • 13
  • 31
  • Works, but kind of dirty IMO - it basically hides the error instead of correcting it. Perfect for demos and quick scripts, but not for production – Nino Filiu Dec 23 '18 at 13:52
9

Just for reference, I am using Angular 7.1.4, TypeScript 3.1.6, and the only thing I need to do is to add this line in tsconfig.json:

    "types": ["node"], // within compilerOptions
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hearen
  • 7,420
  • 4
  • 53
  • 63
  • 1
    did that. Still got this error: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. - did npm install. – Suisse Jan 14 '20 at 10:38
7

I found the solution was to use the TSD command:

tsd install node --save

Which adds/updates the typings/tsd.d.ts file and that file contains all the type definitions that are required for a node application.

At the top of my file, I put a reference to the tsd.d.ts like this:

/// <reference path="../typings/tsd.d.ts" />

The require is defined like this as of January 2016:

declare var require: NodeRequire;

interface NodeModule {
    exports: any;
    require: NodeRequireFunction;
    id: string;
    filename: string;
    loaded: boolean;
    parent: any;
    children: any[];
}
rmlarsen
  • 177
  • 1
  • 13
AlexStack
  • 16,766
  • 21
  • 72
  • 104
5

I took Peter Varga's answer to add declare var require: any; and made it into a generic solution that works for all .ts files generically by using the preprocess-loader:

  1. install preprocessor-loader:

    npm install preprocessor-loader
    
  2. add the loader to your webpack.config.js (I'm using ts-loader for processing TypeScript sources):

    module: {
        loaders: [{
            test: /\.tsx?$/,
            loader: 'ts-loader!preprocessor?file&config=preprocess-ts.json'
        }]
    }
  1. Add the configuration that will add the workaround to every source:
{
    "line": false,
    "file": true,
    "callbacks": [{
        "fileName": "all",
        "scope": "source",
        "callback": "(function shimRequire(source, fileName) { return 'declare var require: any;' + source; })"
    }]
}

You can add the more robust require.d.ts the same way, but declare var require: any; was sufficient in my situation.

Note, there's a bug in preprocessor 1.0.5, which cuts off the last line, so just make sure you have an extra line space return at the end and you'll be fine.

Community
  • 1
  • 1
Benny Bottema
  • 11,111
  • 10
  • 71
  • 96
  • 2
    Why was this downvoted? It answers the question and brings something new and significant to the table. Now you don't have to mangle every file individually to satisfy the transpiler and webpack. – Benny Bottema Feb 19 '16 at 17:04
  • Can you explain step 3 more? I'm a newb and don't know where to put this configuration code at. – user441058 Jun 12 '16 at 07:57
  • @user441058, checkout the [GitHub page](https://github.com/artificialtrends/preprocess-loader), step 3 is about the main configuration for the preprocess-loader. – Benny Bottema Jun 12 '16 at 17:03
5

For me it is resolved by adding types to the angular compiler options.

"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"types": [ "node" ]
}
Farida Anjum
  • 529
  • 6
  • 12
4

I've yet another answer that builds upon all previous ones that describe npm install @types/node and including node in tsconfig.json / compilerOptions / types.

In my case, I have a base tsConfig.json and a separate one in the Angular application that extends this one:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": []
 },

My problem was the empty types in this tsconfi.app.json - it clobbers the one in the base configuration.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
HankCa
  • 9,129
  • 8
  • 62
  • 83
4
import * as mongoose from 'mongoose'
BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
basquith16
  • 103
  • 9
4

As approved answer didn't mention possibility to actually create your own typings file, and import it there, let me add it below.

Assuming you use npm as your package manager, you can:

npm i @types/node --save-dev

Then in your tsconfig file:

tsconfig.json

"include": ["typings.d.ts"],

Then create your typings file:

typings.d.ts

import 'node/globals'

Done, errors are gone, enjoy TypeScript :)

Matt
  • 225
  • 3
  • 3
2

I've been struggling from this issue as well. I believe that this works for all release candidates aka rc but I didn't test it though. For @angular rc.2 it works well.

  1. Add core-js as npm dependency in package.json
  2. run typings install core-js --save
  3. remove all "es6-shim" occurances in your package.json. You don't need it anymore.

Cheers!

kucherenkovova
  • 694
  • 9
  • 22
2

Sometime missing "jasmine" from tsconfig.json may cause this error. (TypeScript 2.X)

So add

"types": [
  "node",
  "jasmine"
]

to your tsconfig.json file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
skaveesh
  • 369
  • 6
  • 9
2

Electron + Angular 2/4 addition:

On top of adding the 'node' type to ts.config various files, what eventually worked for me was adding the next to the typings.d.ts file:

declare var window: Window;
interface Window {
  process: any;
  require: any;
}

Note that my case is developing with Electron + Angular 2/4. I needed the require on the window global.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mihaa123
  • 1,012
  • 9
  • 19
1
  1. Did you specify what module to use to transpile the code?
    tsc --target es5 --module commonjs script.ts
    You must do that to let the transpiler know that you're compiling NodeJS code. Docs.

  2. You must install mongoose definitions as well
    tsd install mongoose --save

  3. Do not use var to declare variables (unless necessary, which is a very rare case), use let instead. Learn more about that

Ayman Nedjmeddine
  • 11,521
  • 1
  • 20
  • 31
1

I couldn't get the 'require' error to go away by using any of the tricks above.

But I found out that the issue was that my TypeScript tools for Visual Studio where an old version (1.8.6.0) and the latest version as of today is (2.0.6.0).

You can download the latest version of the tools from:

TypeScript for Visual Studio 2015

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thomas
  • 194
  • 4
1

Just in addition to cgatian's answer, for TypeScript 1.x

If you are still seeing errors, please specifically provide index.d.ts in your compiler options.

"files": [
    "typings/index.d.ts"
]
Vidish Datta
  • 192
  • 8
1

If you can compile code, but Visual Studio 2015 marks 'require' functions as errors with error text cannot find name 'require' or cannot resolve symbol 'require', update TypeScript for Visual Studio 2015 to the latest version (at the moment 2.1.5) and update ReSharper (if you use it) to at least version 2016.3.2.

I had this annoying problem for a while and couldn't find a solution, but I finally resolved it this way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike Eshva
  • 1,078
  • 15
  • 17
1

Add the following in tsconfig.json:

"typeRoots": [ "../node_modules/@types" ]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Make sure you have installed npm i @types/node

0

If you are using Yarn v3 and see this error (cannot find name require) or other node related "cannot find" errors in VSCode, make sure you have Yarn's VSCode sdk plugin installed and have selected the workspace version of Typescript.

Command to install the sdks:

yarn dlx @yarnpkg/sdks

To set the Typescript version:

  1. Select a Typescript file
  2. Press Command + Shift + P
  3. Type Typescript: Select Typescript Version
  • Select "Use Workspace Version"

See https://yarnpkg.com/getting-started/editor-sdks#vscode for more details.

Joshua Dyck
  • 2,113
  • 20
  • 25
-2

If you are facing this issue in a .ts file which is only there to provide you some constant values, then you can just

rename your .ts file to .js file

and the error will not come again.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aavgeen singh
  • 435
  • 4
  • 12
  • Renaming my ts file to js works! It seems it's a hack but it's a personal project so I'll just let that be. You may also need to add "allowJs": true in under compilerOptions in your tsconfig file. – Sunday David Jan 21 '23 at 20:38