TheUnreal
TheUnreal

Reputation: 24462

Using javascript library in angular 2

Assuming I want to use the following library in my angular 2 app: https://github.com/serkanyersen/ifvisible.js

What I need to do?

I tried to update my SystemJS config with:

 var map = {
 `'ifvisible.js': 'node_modules/ifvisible.js'`
}
var packages = {
'ifvisible.js': {defaultExtension: 'js', main:'src/ifvisible.min' }
  };

Also added this to my index.html:

<script src="node_modules/ifvisible.js/src/ifvisible.min.js"></script>

and in my component:

import * as ifvisible from 'ifvisible.js';

I get error TS2307: Cannot find module 'ifvisible.js'.

What's wrong?

Upvotes: 1

Views: 527

Answers (2)

emrhzc
emrhzc

Reputation: 1480

Importing from node modules can be done with only given their typescript definitions. Fortunately invisible.js has one.

Assuming you're working in a folder next to node_modules, add a reference to the top of the file you are importing

/// <reference path="../node_modules/ifvisible.js/ifvisible.d.ts"/>

and also import like;

import ifvisible = require( 'ifvisible');

If you want to use it in runtime javascript, add the script into index.html;

<script src="node_modules/ifvisible.js/src/ifvisible.min.js"></script>

keep in mind that providing node_modules as public folder is not good practice though, I recommend you to copy ifvisible.min.js to a seperate public folder.

Upvotes: 2

joachim_b
joachim_b

Reputation: 213

If you use the angular-cli, you also have to add it to the angular-cli-build.js, like:

'ifvisible/**/*.+(js|js.map|d.ts)'

This will copy the files from node-modules to your dist folder.

Upvotes: 0

Related Questions