Error import javascript library in typescript

2020-04-10 02:10发布

问题:

I want import javascript library. that is akarata library. I import like in suggestion in internet like this:

import * as akarata from 'akarata/dist';

or

import * as akarata from 'akarata';

still get an error like this

Try npm install @types/akarata if it exists or add a new declaration (.d.ts) file containing declare module 'akarata';

but I tried it nothing happened.

and the weird is. just first I type ng serve , because I use angular, the error appear. and after I make a bit change of my project and then I save it. I still get error but my project works. The library works well too.

Is anyone know why it like that?

回答1:

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. TypeScript has its own syntax, function, and variables can have defined types, if you want to use an external library such as akarata you need to declare type definitions for TypeScript. Some libraries include typing file and you don’t need to install TypeScript’s type destination for them. But in case a library does not have .d.ts file, you need to install it.Type Search

since your library does not have type definition (*.d.ts) in TypeScript and Angular

Solution:
Create if the src/typings.d.ts does not exist, otherwise, open it, and add your package to it:

declare module 'akarata'

and import it

import * as akarata from 'akarata';


回答2:

in your angular-cli.json file.

"scripts": [
    "../path" 
 ];

then add in typings.d.ts

declare var akarata:any;