Search code examples
angulartypescriptecmascript-6ecmascript-5

Angular 2+ Import a Non Module into TS


I made a library and it needs to support multiple applications. However one of the sites is non-angular and will not support "modules", hence I am unable to use "export" on my function.

My External library:

var foo = (function() {

    function MyFunction(){
    }

    MyFunciton.prototype.bar(){
    }

    return MyFunction;

}());

My Question: How do I import this into my component.ts without an export?


Solution

  • Include your script in your angular.json file in the scripts section.

      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
           //...
            "scripts": [
              "src/assets/foo.js.js"
            ]
          },
    

    In your component service, declare your variable. You can then use it without typescript complaining.

    //declare this on top of your component/service
    declare let foo: any;
    
    myMethod()
    {
     var inst = new foo();
     inst.bar();//call bar
    }