升级到Angular4后找不到名称"require" [英] Cannot find name 'require' after upgrading to Angular4

查看:113
本文介绍了升级到Angular4后找不到名称"require"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Angular项目中使用Chart.js. 在以前的Angular2版本中,我一直通过使用具有以下特征的"chart.loader.ts"来做得很好:

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';

但是在升级到cli 1.0.0和Angular 4之后,出现错误:找不到名称'require'".

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

重现该错误:

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

在我的"tsconfig.json"中,

In my 'tsconfig.json', I have

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

在"node_modules/@types/node/index.d.ts"中有:

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

declare var require: NodeRequire;

所以我很困惑.

顺便说一句,我经常遇到警告:

BTW, I constantly encounter the warning:

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

尽管我在'.angular-cli.json'中设置了"prefix":".是因为从"angular-cli.json"更改为".angular-cli.json"是原因吗?

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?

推荐答案

问题(如

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

根据生成的生成的with @angular/cli 1.x,具体步骤应为:

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

第1步:

使用以下任一方法安装@types/node:

Install @types/node with either of the following:

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

第2步: 编辑您的 src/tsconfig.app.json 文件,并添加以下内容代替空的"types": [],应该已经存在:

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.

这篇关于升级到Angular4后找不到名称"require"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆