【问题标题】:Cannot find require but already have @types/node installed and configured globally in Angular找不到 require 但已经在 Angular 中全局安装和配置了 @types/node
【发布时间】:2019-11-23 17:31:41
【问题描述】:

我是 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 中的 types 字段。

所以我查看了我的 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"
    ]
  }
}

然后我进行了重建,但仍然找不到“要求”,因此构建失败。

只是为了获得更多信息,这里是指令文件。 Intellisense 建议我将“要求”转换为导入,所以我这样做了,但这似乎也没有解决它。

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);
  }

}

【问题讨论】:

  • 我以前从未需要/导入任何@types 模块。也许你想要的只是: const google = require('googlemaps'); ?
  • 我会发布答案。因为我遵循的指南(链接)和开发人员在他的文件中的内容不同。

标签: typescript angular7 angular-directive angular-require


【解决方案1】:

这是我为解决这个问题所做的。去开发者 github 页面查看他的文件。 (与他的导游所说的不同)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2020-03-15
    • 1970-01-01
    • 2020-03-08
    • 2019-12-12
    • 2020-12-04
    • 2015-07-09
    相关资源
    最近更新 更多