Jquery plugins giving errors $(...).ionRangeSlider not a function - javascript

I am trying to use jquery plugins in my react application. Every time I try to use some jquery third party plugin, I get an error saying $(...).somePlugin not a function. Currently I am trying to use ionRangeSlider. It is giving me error
Uncaught TypeError: (0 , _jquery2.default)(...).ionRangeSlider is not a function
js file
import $ from 'jquery'
import 'bootstrap-tagsinput'
class AddTagSection extends Component {
componentDidMount=()=> {
this.slider = $(this.inputSlider).ionRangeSlider();
}
<div className="irs-wrapper">
<input type="text" ref={node=>this.inputSlider=node} className='input-slider' id="ionSlider-newTag" name="ionSlider"/>
</div>
Below is the function which is getting called in ionRangeSlider.js (plugin)
$.fn.ionRangeSlider = function (options) {
return this.each(function() {
if (!$.data(this, "ionRangeSlider")) {
$.data(this, "ionRangeSlider", new IonRangeSlider(this, options, plugin_count++));
}
});
};
As far as I have read on web, this is a multiple jquery clashes issue.
About my Application: My project has jquery installed via npm. So there is one jquery present in package.json. I have also included jquery in scripts in my index.jade file. So there is another one there.
This is not an issue of jquery placed after plugin's js file. I placed jquery at the top in the scripts of index.jade file.
block head_scripts
script(src='https://code.jquery.com/jquery-3.2.1.min.js')
script(src='/public/ion.rangeSlider.js')
link(href='/public/normalize.css' rel="stylesheet")
link(href='/public/ion.rangeSlider.css' rel="stylesheet")
link(href='/public/ion.rangeSlider.skinFlat.css' rel='stylesheet')
I also tried noConfilct. But that too didn't work.
var $ = jQuery.noConflict();
$( ".slider" ).ionRangeSlider();
I tried including jquery in my webpack config.js file
new webpack.ProvidePlugin({
React: 'react',
$: 'jquery',
jQuery: 'jquery'
}),
Nothing from the above worked. Everytime I got the same error.
How can I solve this?

If your project contains a different version of jQuery than the one specified in ionRangeSlider package.json dependencies and you're using yarn to install your project's dependencies and webpack to bundle the project, then this might be the source of the problem. Yarn will install node_modules even in ion-range-slider folder, which will cause that the webpack will build the project with your jQuery, as well as with the one in ion-range-slider/node_modules. Hence the jQuery versions clash. ionRangeSlider initiates with the first jQuery and your project's jQuery won't contain it.
It's kind of a fault of ionRangeSlider developer because he should not specify the jQuery in dependencies, but instead in peerDependencies.

try changing internal url to external url for rangeslider
<script src="http://ionden.com/a/plugins/ion.rangeSlider/static/js/ion-rangeSlider/ion.rangeSlider.js"></script>
<link rel="stylesheet" href="http://ionden.com/a/plugins/ion.rangeSlider/static/css/ion.rangeSlider.css" />
then do import Slider from 'react-rangeslider' if not using the es6 transpiler then do var Slider = require('react-rangeslider')

I also had this error, looks like a Jquery version conflict please try downgrading ion-rangeslider in package.json "ion-rangeslider": "2.2.0".

Related

Ruby on Rails 6 Webpack with Javascript libraries

I am building a new project in Rails 6. I have a front-end library I want to use (#tarekraafat/autocomplete.js) that is installed by yarn and exists in my node_modules directory, but is not being made available to other JS code in the browser. Here is what I have set up currently:
/package.json:
"dependencies": {
"#tarekraafat/autocomplete.js": "^8.2.1"
}
/app/javascript/packs/application.js:
import "#tarekraafat/autocomplete.js/dist/js/autoComplete.min.js"
/app/views/.../example.html.erb
<script type="text/javascript">
window.onload = () => {
new autoComplete({
[...]
});
};
</script>
I am getting an error in the browser pointing to the new autoComplete():
Uncaught ReferenceError: autoComplete is not defined
Some reading seems to indicate that I need to modify the /config/webpack/environment.js file, in which I have tried various versions of the following with no luck (including restarting the dev server):
/config/webpack/environment.js:
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
autoComplete: 'autocomplete.js'
})
);
module.exports = environment
First, what do I need to do to add this library so it can be used correctly? Second, as someone who has not directly used webpack previously, what is the function of adding this definition to the environments.js file, and why don't I need to do it for some libraries (bootstrap, popper) but I do for others (jquery, and maybe autocomplete.js)?
In Webpacker, the usage of this library would be as follows:
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
new autoComplete(...)
// app/javascript/packs/application.js
import "../src/any_file"
This alone does not import the autoComplete variable into the global scope. To do that, the simplest thing is assign the variable to window from within your webpack dependency graph.
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
window.autoComplete = autoComplete
As an aside, you don't need to use the ProvidePlugin configuration for this library. The ProvidePlugin says: “add this import to all files in my dependency graph.” This might be helpful for something like jQuery to make legacy jQuery plugins work in webpack. It is not necessary to make your autocomplete lib work

Require.js define object is somehow being inserted to my code - gulp.js

I'm running a gulp-concat script, which concats jquery, slick-carousel, t.js and my index.js files.
const pack = () => {
return gulp.src(['./node_modules/jquery/**/jquery.js', './node_modules/slick-carousel/**/slick.js', './assets/js/t.js-master/t.js', './js/index.js'])
// .pipe(gulp_babel({
// 'presets': ['#babel/env'],
// 'plugins': ["transform-remove-strict-mode"]
// }))
.pipe(gulp_concat('main.js'))
// .pipe(gulp_uglify())
.pipe(gulp.dest('./build'));
}
As you can see, I removed any pipes that might be causing the issue. The only task running is gulp-concat. (index.js is all in ES5 and I'm running on latest version of firefox, no need for babel atm) When I open my page, however, I get the error
Uncaught ReferenceError: define is not defined
Looking at main.js, I found a define object at the end of the jquery section - but only in the concatinated file, not the jquery in node_modules. I didn't add this, and I'm not using require.js as far as I know:
define( [
"./core",
"./selector",
"./traversing",
"./callbacks",
"./deferred",
"./deferred/exceptionHook",
"./core/ready",
"./data",
"./queue",
"./queue/delay",
"./attributes",
"./event",
"./event/focusin",
"./manipulation",
"./manipulation/_evalUrl",
"./wrap",
"./css",
"./css/hiddenVisibleSelectors",
"./serialize",
"./ajax",
"./ajax/xhr",
"./ajax/script",
"./ajax/jsonp",
"./ajax/load",
"./core/parseXML",
"./core/parseHTML",
"./effects",
"./effects/animatedSelector",
"./offset",
"./dimensions",
"./deprecated",
"./exports/amd",
"./exports/global"
], function( jQuery ) {
"use strict";
return jQuery;
} ); // jQuery seems to end here
How is this extra code being added, and how might I avoid it? I'm also using browserSync, but don't think that's related.
I've just checked the source of jQuery and there is a file:
https://github.com/jquery/jquery/blob/3.5.1/src/jquery.js
So what you need to do is to simply exclude it and it should fix the issue :)

Importing JS files outside Webpack

So, i have a script that creates a global object
(function() {
window.GlobalThing = {}
})();
This script will also fill this object attributes
if (!GlobalThing .Resource) { GlobalThing .Resource = require('./Resource'); }
Then, some other scripts that are not bundled with webpack need to use this GlobalThing. I`ve tryed to make it global using ProvidePlugin for example:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
'GlobalThing': path.join(__dirname,"Path/GlobalThing.js")
})
],
I've tryed adding an Alias as well
resolve: {
alias: {
'GlobalThing': path.join(__dirname,"Path/GlobalThing.js")
}
}
I have tryed doing something like this in the end of my GlobalThing.js file as well:
(function(){
window.GlobalThing = GlobalThing;
})();
Then i had to import to run the script, so i got a random js file inside the webpack to test it:
import GlobalThing from "GlobalThing ";
Still, it seems some scripts cannot seethe GlobalThing. If i bundle everything up with webpack, it works, but i didnt want to as our app is very old and have some very old stuff. Is there a way i can expose GlobalThing to those older scripts ?
ProvidePlugin takes a module name (i.e. string) and internally uses require to load it. So that wont help you in loading your own script.
That said, following should work:
Keep the GlobalThing script out of webpack bundling
Make sure the script itself is copied to the output folder
Make sure the index.html (or whatever html page you are using) has the scripts in the order GlobalThingScript.js followed by webpack bundle.js
To give you more insight:
When webpack bundles the scripts other than GlobalThingScript.js, it doesnt even know there is something called GlobalThing. It just bundles the other files.
That would mean it is upto you to make sure the GlobalThingScript.js is also made it to the final output folder. Also, the html source should use <script> tags to include the GlobalThingScript.js before webpack bundle.js.
In case problem persists, please do edit the OP to include the html source.
Hope that helps.

How to properly configure requireJS

Hi I'm trying to make starting template for SPA project mainly using:
RequireJS, KnockoutJS, TypeScript, etc.
I'm having hard time figuring out how to configure paths and folder structure for RequireJS to work properly...
here is my folder structure:
Scripts
app
components
main.js
lib
knockout.js
jquery.js
here is my RequireJS config file:
var config = {
waitSeconds: 15,
paths: {
app: '../app',
'knockout': '/lib/knockout-3.4.2.',
sammy: '/lib/sammy-0.7.5.',
jquery: '../scripts/lib/jquery-1.10.2.'
}
};
This is my attempt for main.js:
define(['jquery', 'PageOne', 'PageTwo'], function ($, pageOne, pageTwo) {
$(document).ready(function () {
var app = Sammy('#main', function () {
this.get('#/pageOne', function () {
pageOne.activate();
});
this.get('#/pageTwo', function () {
pageTwo.activate();
});
});
app.run();
});
});
Here is my Index.cshtml script tag:
<script src="~/Scripts/lib/require.js" data-main="scripts/app/components/main"></script>
I saw in different project that config is called in header so this is in html header:
<script src="~/Scripts/app/config/require.config.js"></script>
My problem is that in main.js it looks for jquery under path defined in data-main (scripts/app/components/), but my jquery is in scripts/lib folder.
I'm trying to figure out by reading online the whole day but it's too much time for me I need someone to give me some hints how is this supposed to work?
Seriously having hard time figuring this out and RequireJS website just isn't helping me atm.
Note: I am beginner in JavaScript based projects, first SPA attempt,
never used RequireJS...
Your configuration file does not do anything. I'm assuming from your description that the script element that loads it is located before the script element that loads RequireJS. That's one valid way to configure RequireJS, but if you want RequireJS to pick up the configuration, you need to set the global variable require before you load RequireJS, and RequireJS will use the value of require as its configuration. Right now you are setting config, which is ignored by RequireJS. So:
var require = {
waitSeconds: 15,
// etc...
And once the configuration is in effect, you should be able to reduce your data-main to data-main="components/main".
I see some of your paths in the paths configuration end with a dot. That's most likely a mistake on your part, or you have some very strange file names.

Use jspm to load script that depends on global jQuery

Yes I've read How do I shim a non CommonJS, non AMD package which depends on global jQuery & lodash?.
I'm trying to load X.js, through jspm, which is not a 'package' but an old js file I have no control over that needs a global jQuery object and needs to run like it is in a script tag.
I'm using System.import('app/X'); to load it.
I tried various shim / globals tricks to make it load but I can't quite figure it out.
How would one write the config.js to be able to import that X file so that it sees a global jQuery object? Do I have to make X a 'package' and install it to be able to shim it better?
Thanks.
If you installed jquery through jspm, all you need is to set the meta 'deps' property like this:
System.config({
meta: {
'app/X': {
deps: ['jquery']
}
}
});
System.import('app/X');
Be sure to get the X path correctly and check how jspm sets up System.config 'paths' and 'map', by default trailing .js is added automatically (with paths *.js wildcard) so you must not add it.
Maybe try to look at these links from the documentation as well https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md#globals https://github.com/systemjs/systemjs/blob/master/docs/config-api.md#meta
If providing the meta 'deps' property like the following (as suggested by Mathias Rasmussen) doesn't do the trick,
System.config({
meta: {
'app/X': {
deps: ['jquery']
}
}
});
then you may have to provide a 'globals' meta property like the following:
System.config({
meta: {
'app/X': {
globals: {
'jquery': 'jquery'
}
}
}
});
In order for the above to work you will have needed to install jquery via jspm. Doing the above should also allow you to import the plugin by doing System.import('app/X'); or import 'app/X'; without having to import jquery as well. Importing the plugin alone should also bring in jquery as a dependency.

Categories

Resources