【问题标题】:Importing a 3rd party library into Angular2 /TS将第 3 方库导入 Angular2 /TS
【发布时间】:2018-04-10 04:11:57
【问题描述】:

我在将 this 库导入 Angular2/Ionic 项目时遇到问题。它是一个围绕原始加速度计数据进行一些计算的库。该示例说明我需要做一个require('ahrs'),我正在尝试在打字稿中做。过去,我需要做的就是将 js 文件复制到可以访问的目录并为其声明一个变量。这种方法适用于其他库,但在这里出错。这是我所做的:

第 1 步:通过自定义 copy.config 将 JS 文件复制到我的项目构建目录

copyAHRS: {
        src: './external/www-ahrs.js',
        dest: '{{BUILD}}'
  },

这很好 - 我可以在我的构建中看到 www-ahrs.js

第 2 步:将文件包含在我的index.html

 <script src="build/www-ahrs.js"></script>

这也很好用。

第 3 步:尝试在我的代码中(在组件中)使用它。此代码直接来自 AHRS 库 readme。这个错误。

declare var ahrs:any;

    try {
              madgwick = new ahrs({
              sampleInterval: 20,
              algorithm: 'Madgwick',
              beta: 0.4,
              kp: 0.5,
              ki: 0
          }); 

      }
      catch (e) {
        console.log ("MADGWICK ERROR " + JSON.stringify(e))
      }

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您需要使用 npm 安装它,然后在 *ts 文件的顶部声明它。这是一个使用lodash的示例:

    import {Component, OnInit} from '@angular/core';
    import {Router} from '@angular/router';
    const _ = require('lodash');
    
    @Component({
        selector: 'my-component',
        templateUrl: './my-component.component.html',
        styleUrls: ['./my-component.component.scss']
    })
    

    你会是

    const ahrs = require('ahrs');
    

    【讨论】:

    • 我是否需要将其复制到我的构建文件夹并包含在&lt;script src&gt; 中,还是我需要做其他事情?如果我在上面做一个要求,它就找不到它。
    • 啊,没关系,我没有手动安装,而是通过npm 安装了它,并且要求代码完美运行!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多