ALansmanne
ALansmanne

Reputation: 331

In Angular 5, how can I import NPM modules with no @types

I'm trying Angular 5, starting a project from angular-cli. In this project, I would like to use a NPM module : J2M (https://github.com/kylefarris/J2M), so I looked online and saw these two commands :

npm install j2m --save
npm install @types/j2m --save-dev

Unfortunately, @types/j2m doesn't exist at all. So I tried to find a way to define my own typings but didn't manage to succeed...

I'm using this code :

import * as J2M from "j2m";
...
console.log(J2M.toM(value));

But either "j2m" is not recognized, or "toM" is not a function, based on the samples I found online...

So, what's the proper way to import this module?

Thanks,

Upvotes: 11

Views: 25608

Answers (1)

user4676340
user4676340

Reputation:

You need to add the scripts into your angular-cli.json file.

Under the scripts property, add

'../node_modules/path/to/minified/js.js'

If a style is required, you must also add it under your styles property, in the same file.

Once you did that, your library is imported. This means you don't need to use such things as

import * from 'j2m';

But if you want to use a global variable without your IDE throwing errors, then you should add

declare var J2M: any;

with J2M being the exported, global function from your library (for instance, for MomentJS, this variable is called moment).

When you use a definition file, it just tells the CLI to automatically fetch the JS library, and gives you IDE auto-completion. With this solution, you don't have auto-completion, and you explicitly tells the CLI where to fetch the library.

Upvotes: 22

Related Questions