Search code examples
angularionic4capacitor

How to use third party javascript library with ionic4 and capacitor?


What is the correct way to install third party javascript libraries with an Ionic 4 angular app and Capacitor?


I tried to install the crunker library as follows:

npm install crunker --save

Then ...

import * as crunker from 'crunker';
...
export class MyPage {

  constructor() {}

  doX() { 
     const crunk = new crunker.Crunker();
     ...
  }
  ...
}

Followed by:

npm run build
npx cap copy
npx cap copy ios
npx cap open ios

However, when I hit the page in the IOS simulator, I see the following error in the console:

TypeError: undefined is not a constructor (evaluating 'new crunker__WEBPACK_IMPORTED_MODULE_4__"Crunker"')


Update:

I have tried adding crunker to angular.json, as per this answer, but I get the same error.


Solution

  • Open angular.json and add script into scripts section.

    "scripts": [
      "../node_modules/crunker/dist/crunker.js"
    ]
    

    Important thing is to do npx cap copy after rebuild project