serlingpa serlingpa - 1 month ago 25
Node.js Question

Angular 2.0.0-beta.15 & webpack: "Cannot find the name 'require'."

I have recently upgraded my webpack-based Angular 2 app from 2.0.0-beta.2 to 2.0.0-beta.15. I received a lot of errors on compiling, a lot of which were resolved by adding the line:

/// <reference path="../node_modules/angular2/typings/browser.d.ts" />


to my bootstrap file. However, I am still receiving a lot of errors pertaining to
require
:

error TS2304: Cannot find name 'require'.


The TypeScript loader is using version 1.8.10 of the compiler, and my tsconfig.json looks like this:

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noEmitHelpers": false,
"sourceMap": true,
"moduleResolution": "node"
},
"filesGlob": [
"./app/**/*.ts",
"!./node_modules/**/*.ts"
],
"compileOnSave": false,
"buildOnSave": false
}


What else do I need to do to get this working? This is a real blocker for me!

Answer

You should use a tool such as typings to add type definitions for your modules.

Install it globally:

npm i -g typings

Create a config for it:

typings init

There's a type definition for using require.

typings install require --ambient --save

Be aware that typings will add type definitions for main and for the browser, make a change on your tsconfig.json file to only include the browser version.

"filesGlob": [
    "./app/**/*.ts",
    "!./node_modules/**/*.ts",
    "!./typings/main",
    "!./typings/main.d.ts"
  ],