Cannot find name 'require' after upgrading to Angular4

Thomas Wang picture Thomas Wang · Mar 29, 2017 · Viewed 108.1k times · Source

I want to use Chart.js within my Angular project. In previous Angular2 versions, I have been doing this well by using a 'chart.loader.ts' which has:

export const { Chart } = require('chart.js');

Then in the component code I just

import { Chart } from './chart.loader';

But after upgrading to cli 1.0.0 and Angular 4, I get the error: "Cannot find name 'require'".

To reproduce the error:

ng new newapp
cd newapp
npm install chart.js --save
echo "export const { Chart } = require('chart.js');" >> src/app/chart.loader.ts
ng serve

In my 'tsconfig.json', I have

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

And in 'node_modules/@types/node/index.d.ts' there is:

declare var require: NodeRequire;

So I'm confused.

BTW, I constantly encounter the warning:

[tslint] The selector of the component "OverviewComponent" should have prefix "app"(component-selector)

Though I have set the "prefix": "" in my '.angular-cli.json'. Could it because changing from 'angular-cli.json' to '.angular-cli.json' the cause?

Answer

IndyWill picture IndyWill · Mar 31, 2017

The problem (as outlined in typescript getting error TS2304: cannot find name ' require') is that the type definitions for node are not installed.

With a projected genned with @angular/cli 1.x, the specific steps should be:

Step 1:

Install @types/node with either of the following:

- npm install --save @types/node
- yarn add @types/node -D

Step 2: Edit your src/tsconfig.app.json file and add the following in place of the empty "types": [], which should already be there:

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

If I've missed anything, jot a comment and I'll edit my answer.