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

查看:37
本文介绍了升级到 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"中设置了前缀":".可能是因为从 '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?

推荐答案

问题(如打字稿出现错误 TS2304: 找不到名称 'require') 是因为未安装节点的类型定义.

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天全站免登陆