user1361529
user1361529

Reputation: 2697

Importing a 3rd party library into Angular2 /TS

I am facing a problem importing this library into an Angular2/Ionic project. It is a library that does some calculations around raw accelerometer data. The example states I need to do a require('ahrs') which I'm trying to do in typescript. In the past, all I've needed to do was to copy over the js file to a directory which can be accessed and declare a variable for it. That approach works great for other libraries, but is error-ing here. Here is what I did:

Step 1: Copy the JS file to my project build directory via a custom copy.config

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

This works fine - I can see www-ahrs.js in my build

Step 2: Include the file in my index.html

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

This works fine too.

Step 3: Try to use it in my code (in a component). This code is directly from the AHRS library readme. This errors.

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

Upvotes: 0

Views: 60

Answers (1)

Chris Sharp
Chris Sharp

Reputation: 1995

You need use npm to install it and then declare it at the top of your *ts file. Here's an example using 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']
})

Yours would be

const ahrs = require('ahrs');

Upvotes: 1

Related Questions