Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Created December 27, 2018 09:30
Show Gist options
  • Save vxhviet/cd2aa8808ed077cf11f6b6cb616ca89f to your computer and use it in GitHub Desktop.
Save vxhviet/cd2aa8808ed077cf11f6b6cb616ca89f to your computer and use it in GitHub Desktop.

Import JavaScript library into Angular

SOURCE, SOURCE

What works in Angular 7:

The JS library trie-search doesn't have the definition .dt.ts file to be used in TypeScript file. so we need to use the following method in order to use it.

Tips: using Type Search to see if there's any pre created .d.ts for your library SOURCE.

  1. Add links to your JS library in angular.json:
"architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            ...
            
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/bootstrap/dist/js/bootstrap.bundle.js",
              "node_modules/slick-carousel/slick/slick.min.js",
              "node_modules/hasharray/dist/HashArray.js", // TriSearch also use this library
              "node_modules/trie-search/src/TrieSearch.js"
            ]
          },
  1. Stop and build project again with ng s.

  2. After this, you can declare and use TrieSearch as the following:

declare var TrieSearch: any;

@Component({
  selector: 'app-find-doctor',
  templateUrl: './find-doctor.component.html',
  styleUrls: ['./find-doctor.component.scss']
})
export class FindDoctorComponent implements OnInit {

  ....
  
  const ts = new TrieSearch();
}
  1. If it doesn't work, then use this method instead. Create this file src/typings.d.ts with the following:
declare module 'hasharray';
declare module 'trie-search';
  1. Then import and use it like this:
import * as TrieSearch from 'trie-search';

const ts: any = new TrieSearch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment