11

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,

ALansmanne
  • 271
  • 1
  • 6
  • 17

1 Answers1

22

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.

  • Perfect ! Thats works :) Accepting as best solution. – ALansmanne Feb 13 '18 at 08:03
  • Oh, another "problem" appeared when I tried to siwtch to the forked version of J2M, that uses "require('marked') ReferenceError: require is not defined And later on TypeError: J2M is undefined probably because it failed to import marked... – ALansmanne Feb 13 '18 at 08:44
  • Then don't switch to it :D Otherwise, take a look at [this issue](https://stackoverflow.com/questions/12742082/nodejs-require-inside-typescript-file) to resolve it –  Feb 13 '18 at 08:46