1

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?

TheUnreal
  • 23,434
  • 46
  • 157
  • 277

2 Answers2

2

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.

emrhzc
  • 1,347
  • 11
  • 19
  • I has to write both of the those lines in my component.ts? Because that's what I did, and I get: `GET http://localhost:3000/ifvisible 404 (Not Found)` – TheUnreal Jun 26 '16 at 12:46
  • using a module in angular2 and in runtime are two different things. importing like above will only give you ability to use in your angular2 component class. If you want to use it during runtime, follow instructions I added above. – emrhzc Jun 26 '16 at 18:32
  • `Failed to load resource: the server responded with a status of 404 (Not Found)` – TheUnreal Jun 27 '16 at 16:24
0

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.

joachim_b
  • 173
  • 11