'using slick-carousel with typescript
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!
Solution 1:[1]
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
Solution 2:[2]
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 :).
Solution 3:[3]
- install
jquery - install
slick-carousel - install
@typings\slick-carousel - Add
slick.cssfrom thenode_modules - 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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ayushi Jain |
| Solution 3 |
