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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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)
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.
Failed to load resource: the server responded with a status of 404 (Not Found)
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.

2 Comments

Not using angular-cli
How to import / use ifvisible into component?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.