using slick-carousel with typescript

5.1k views Asked by At

Im new to typescript and im trying to get the a hang on the concept of how modules/packages works in typescript..

I am currently in the need of using slick-carousel to create a simple image slider.

However.. I have managed to install jquery.. but I dont quite get how to get slick to work with typescript.

So far I have used npm typings to install my packages.

So I just ran typings install slick-carousel.. and the definition-file showed up fine.. however.. the definition-file contains no declaration only interfaces.. So I cant really "import" slick-carousel into the file where I need to use it (I might be wrong).. so I guess that the package is supposed to extend the already existing jquery import in some why..

However.. If I do this:

import * as $ from 'jquery';

class Splash {
    init() {
        $.slick();
    }
}

then

$.slick();

cant be resolved..

so.. how do you "import" a package that only extends a pre-existing package like jquery?

Thanks in advance!

3

There are 3 answers

2
Jesse Johnson On

Using an AMD module loader (example RequireJS) would ensure your code only runs once all external modules, and their dependencies, have been loaded.

Here is an example using RequireJS with a shim config:

index.html    

<head>
    <title>jQuery++Slick+RequireJS Sample Page</title>
    <script data-main="app" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.js"></script>
</head>

<body>
    <h1>jQuery++Slick+RequireJS Sample Page</h1>
    <p>Look at source or inspect the DOM to see how it works.</p>
</body>

</html>

app.js (after compiled from app.ts)

requirejs.config({
    baseUrl: ".",
    paths: {
        "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"
        "slick": "https://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js"
    },
    shim: {
        'jquery': {
            exports: '$'
        }
        'slick': {
            deps: ['jquery'],
            exports: '$.fn.slick'
        }
    }
});

requirejs(["jquery", "slick"], function($) {

    // Code within this function will only execute
    // once jQuery and Slick have been loaded.
    //
    // The configuration above ensures jQuery will always 
    // be loaded before slick.

    $.slick();

});

The RequireJS documentation has a whole section on how to use with jQuery

0
Ayushi Jain On

you will need to declare $ . you can use declare var $: any;

declare var $: any;
class Splash {
    init() {
        $.slick();
    }
}

It won't give you error anymore :).

0
Amir Shirazi On
  1. install jquery
  2. install slick-carousel
  3. install @typings\slick-carousel
  4. Add slick.css from the node_modules
  5. optional: Add slick-theme.css.

At the top of the TS file add these 2 imports:

import $ from 'jquery';
import 'slick-carousel';

Then use it like below:

$('.your-class').slick()