简体   繁体   中英

How do I inject/integrate a third party library in Angular 6?

Some libraries are not supported by Angular like Clappr , HashWords etc . I want to use them in Angular as if they were an Angular library . So how can we make Angular support external libraries/modules ?

If the library has a ES6 module, you can just import it.

If the library is just a JS file, you can add the file as if you where importing it using a <script> tag on index.html by adding the js file path on the scripts array in angular.json

If types are available you can add them to the types array on typescript.json

Here is a guide to do all that.

https://nitayneeman.com/posts/how-to-add-third-party-library-in-angular-cli/

If you dislike having the third party libraries as global variables you can turn them into inyectables. it's a more involved process but it's pretty neat.

Here is a guide for that too:

https://hackernoon.com/angular-providers-how-to-inject-3rd-party-library-af4a78722864

Here's how I installed in my Angular 9 project:

  1. npm install clappr
  2. Add clappr into angular.json :
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "scripts": [
            "node_modules/clappr/dist/clappr.min.js"
          ],
          "styles": [
            "./src/styles.css"
          ]
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "scripts": [
            "node_modules/clappr/dist/clappr.min.js"
          ],
          "styles": [
            "./src/styles.css"
          ]
        }
      }

  1. Create file index.d.ts and declare clappr as:
declare module 'clappr';
  1. import it into component.ts file:
import * as Clappr from 'clappr';
  1. Install the package into your project : npm i clappr
  2. Import type declaration into Angular app : app.component.ts

Add the library file in index.html. The variable exposed by the library can be used in component by declaring like this declare var Clappr: any; outside the component class.

For Clappr- In Angular CLI, run the command-

npm i clappr

https://www.npmjs.com/package/clappr

Then follow the steps given..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM