Search code examples
angularangular7typescript-typingsexternal-jswordcloud2

angular error: WordCloud is not a function


i am still prety new to angular, i was trying to use wordcloud2 in my app and got an error WordCloud is not a function when trying to call the function.

wordcloud2.js contains the WordCloud function, I tried to import it, but I encoded the problem described above, i think i am missing something, i think the declaration is recognized but not the function.

please see this code example attached:

https://stackblitz.com/edit/angular-7hsahs

angular error: WordCloud is not a function


Solution

  • Change line 2 from
    import * as WordCloud from 'wordcloud';
    to:
    import WordCloud from 'wordcloud';

    The difference between the two import statements is that the one you used will import the whole module as one object, and the WordCloud() function is a property of it. That is not supported by the type definition, so TypeScript will throw an error, since you incorrectly told TypeScript the type of the imported module.
    If you instead import it with import WordCloud from 'wordcloud';, you instead get only the function that is described as being exported by default in the type declaration.

    Basically you have several different forms of exports:

    export function foo() {return "bar";}
    export const BAR = "foo";
    

    Here, you can import the different variables like this:

    import {foo, BAR} from './foobar';
    console.log(foo(), BAR); // "bar", "foo"
    

    or this:

    import * as foobar from './foobar';
    console.log(foobar.foo(), foobar.BAR); // "bar", "foo"
    

    or you have an export with a default export like this:

    export default function foo() {return 'bar';}
    

    in which case you can import like this:

    import foo from './foo';
    console.log(foo()); // "bar"
    

    or this:

    import {default as foo} from './foo';
    console.log(foo()); // "bar"
    

    Although, if a default export is given, you can name the imported variable anything you want. In the example above, import bar from '.\foo'; would work, too, and invoking bar() would return "bar". That is because the exported variable basically does not have its name exported, but has the special name "default" instead.

    You can read up a bit more about importing in TypeScript here:
    https://blog.jdriven.com/2017/06/typescript-and-es6-import-syntax/