找不到要求,但已在Angular中全局安装和配置@ types / node

时间:2019-07-15 02:03:58

标签: typescript angular7 angular-directive angular-require

我是Angular的新手,只是尝试为google maps autocomplete创建我的第一个指令。但是我在directive.ts文件中有问题。 在顶部,我有一个找不到的要求,因此无法构建应用程序。

  

const google = require('@ types / googlemaps');

错误消息说

  src / app / _directives / google-places.directive.ts(2,16)中的

错误:错误TS2580:找不到名称“ require”。您是否需要为节点安装类型定义?尝试npm i @types/node,然后将node添加到tsconfig的类型字段中。

所以我查看了package.json文件中的“ @ types / node”,然后看到了。

   "devDependencies": {
"@angular-devkit/build-angular": "~0.13.0",
"@angular/cli": "~7.3.9",
"@angular/compiler-cli": "~7.2.0",
"@angular/language-service": "~7.2.0",
"@fortawesome/fontawesome-pro": "^5.9.0",
"@types/jasmine": "~2.8.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~4.5.0",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.2.2"
}

然后我查看了tsconfig.json中的类型,没有看到它,所以我添加了它。

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "types": [
      "node"
    ]
  }
}

然后我进行了重建,但是仍然找不到'require',因此构建失败。

仅提供其他信息,这是指令文件。 Intellisense建议我将“ require”转换为导入,所以我做到了,但这似乎也没有解决。

import {
  Directive,
  OnInit,
  ElementRef
} from '@angular/core';
const google = require('@types/googlemaps'); // error here with require
// import google = require('@types/googlemaps'); // doesn't work either

@Directive({
  selector: '[appGooglePlaces]'
})

export class GooglePlacesDirective implements OnInit {
  private element: HTMLInputElement;

  constructor(private elRef: ElementRef) {
    // elRef will get a reference to the element where
    // the directive is placed
    this.element = elRef.nativeElement;
  }

  ngOnInit() {
    const autocomplete = new google.maps.places.Autocomplete(this.element);
  }

}

1 个答案:

答案 0 :(得分:0)

这就是我要做的事情。进入devs github页面并查看了他的文件。 (与他的向导说的不同)

A。他没有像他的指南中那样导入@ types / googlemaps B.在指令顶部///