在 angular 6 中找不到 HammerJS

Could not find HammerJS in angular 6

我在我的项目中使用 angular-material。我收到此警告:

Could not find HammerJS. Certain Angular Material components may not work correctly.

The "longpress" event cannot be bound because Hammer.JS is not loaded and no custom loader has been specified.

我知道这是这个的副本

他们在回答中提到:

  1. 我们必须在 package.json 文件中将 "^2.0.8", 添加到 dependencies
  2. polyfills.ts 文件中导入 'hammerjs/hammer';

在我的情况下一切都很好,但我仍然收到相同的警告 浏览器控制台。

有两种方法可以解决这个问题:

  1. 要么在主模块文件中包含 (main) 导入,要么 polyfills.ts:

    import 'hammerjs';
    
  2. 或者将来自 CDN 的脚本包含到您的 index.html 文件中:

    <head>
      <!-- ... -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
      <!-- ... -->
    </head>
    

使用 angular6,你可以在 angular.json 文件的 node_modules 中包含 hammerjs 路径。

Angular doc 表示 angular.json 文件的目的是

CLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses, such as TSLint, Karma, and Protractor. For details, see Angular Workspace Configuration.

您可以在脚本列表中包含 hammerjs 节点模块路径。请参阅下面的示例:

 "projects": {
    "demo": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/demo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/manifest.json"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": [
              "node_modules/hammerjs/hammer.min.js" <- add path to hammerjs
            ]
          },
          "configurations": {
          ....

注意需要重启ng serve才能生效。

安装

npm install --save hammerjs

yarn add hammerjs

安装后,将其导入您应用的入口点(例如 src/main.ts)。

import 'hammerjs';

Angular Material Getting Started Guide

项目全局级添加hammer js

"scripts": [
              "node_modules/hammerjs/hammer.min.js" <- add path to hammerjs
            ]

模块级别添加

import * as Hammer from 'hammerjs';

对于 Angular Material 的新版本,当您安装 Material 时,您只需要 运行

ng add @angular/material

它会问你这样的问题

Set up HammerJS for gesture recognition?

您应该回答“Y”,它会自动为您配置 HammerJS。

Angular Material 安装指南:https://material.angular.io/guide/getting-started#install-angular-material