How to call bootstrap's jQuery plugins in ES6 - javascript

I'm stuck trying to call the bootstrap's jQuery plugins, like popover, tooltip, modals, ...
I'm using webpack and this is my ES6 javascript:
import $ from 'jquery';
//import Bootstrap from 'bootstrap-sass';
//import Bootstrap from 'bootstrap-loader';
import Bootstrap from '../vendor/bootstrap.min.js';
class Test {
constructor () {
$('[data-toggle="tooltip"]').tooltip({ html: true });
}
}
I've tried to install bootstrap with npm, but after that i wasn't sure which one node-modules i had to import (like you can see in commented lines in the imports). So, i thought to import directly the bootstrap.min.js.
The fact is that i still have an error (independently if i try with popover/modals/tooltip) like this in my app.js that is my javascript generated from the webpack:
Uncaught TypeError: (0 , _jquery2.default)(...).tooltip is not a function
Like i say, i'm stuck here.
Last thing, the boostrap CSS works correctly thanks to this:
gulp.task('bootstrap-fonts', function() {
return gulp.src('node_modules/bootstrap-sass/assets/fonts/bootstrap/*')
.pipe(gulp.dest('./app/assets/fonts/bootstrap'));
});
gulp.task('dev', ['css', 'bootstrap-fonts', 'browser-sync', 'webpack'], function () {
gulp.watch('src/scss/**/*.scss', ['css']);
gulp.watch('src/js/**/*.js', ['webpack']);
gulp.watch('app/*.html', ['bs-reload']);
});

Because the bootstrap library depends on jQuery,
you should try to add the following plugin to the 'plugins' array in your webpack.config.js so that the bootstrap module will use the jQuery global object:
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": 'jquery'
}),
This plugin will actually injects the 'jquery' module in any other module that ask for him (means, every module that use the objects jQuery or $ or window.jQuery), and bootstrap is one of them.

Related

Bootstrap tooltip is not a function, Popper not working

I'm trying to use separate modules of bootstrap in my website instead of include the whole minified file. But I'm freaking out, why is that so complicated? Or I'm complicating this?
"devDependencies": {
"exports-loader": "1.1.1",
"webpack": "4.39.2",
"uglify-js": "3.6.0",
},
"dependencies": {
"bootstrap": "4.3.1",
"jquery": "3.4.1",
"popper.js": "1.14.7",
}
custom bootstrap.js in /js
/* Tries:
import $ from 'jquery';
import 'popper.js';
import 'popper.js/dist/umd/popper.js';
import 'popper.js/dist/umd/popper.min.js';
import 'bootstrap/dist/js/bootstrap.min.js'; */
window.jQuery = $;
window.$ = $;
global.$ = $;
/* BOOTSTRAP CUSTOM IMPORTS */
import 'bootstrap/js/dist/util';
import 'bootstrap/js/dist/alert';
import 'bootstrap/js/dist/button';
import 'bootstrap/js/dist/collapse';
import 'bootstrap/js/dist/dropdown';
import 'bootstrap/js/dist/modal';
import 'bootstrap/js/dist/tooltip';
import 'bootstrap/js/dist/popover';
import 'bootstrap/js/dist/tab';
With that, my code compile with success but on chrome console this error appear
Uncaught TypeError: $(...).tooltip is not a function
If I include this on my webpack.config.js:
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
'window.jQuery': 'jquery/src/jquery',
Popper: ['popper.js', 'default'],
}),
The tooltip error is gone, but starts to do error on other libs, like:
//Error on chrome console
Uncaught TypeError: $(...).mask is not a function
My Loading order of JS is:
LIBS (A WEBPACK MERGED FILE WITH ALL OTHER LIBS, LIKE JQUERY, MASKS, SLICK...)
BOOTSTRAP
POLYFILL
Searching the internet I see that a lot of people are experiencing this problem but the solutions they present are not working for me.
Please, anybody can help me?
Thanks for responses.
I figured out what is going on, not really understanding why but, bootstrap imports with JQuery were causing conflicts in the use of jquery by plugins, so, I had to remove jquery imported from bootstrap file then include manually on another process of plugins file, like that:
/* BOOTSTRAP.js CUSTOM IMPORTS */
//removed jquery imports
import 'bootstrap/js/dist/util';
import 'bootstrap/js/dist/alert';
import 'bootstrap/js/dist/button';
...
webpack.config:
//I had to maintain that provider
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
Popper: ['popper.js', 'default'],
}),
new MergeIntoSingleFilePlugin({
files: {
"js/libs.base.js": [
//included jquery min file on merge of plugins
path.join(source, 'src/libs/jquery', 'jquery-3.4.1.min.js'),
path.join(source, 'src/libs/jquery-mask', 'jquery.mask.min.js'),
...
I think this can help.
// TOOLTIP PLUGIN DEFINITION
// =========================
var old = $.fn.tooltip
$.fn.tooltip = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})

Bootstrap 4 Beta importing Popper.js with Webpack 3.x throws Popper is not a constructor

So Bootstrap 4 Beta is out... yey! However Tether has been replaced by Popper.js for tooltip (and other features). I saw an error thrown in the console fast enough to advise me of the change to Popper.js:
Bootstrap dropdown require Popper.js
Seems easy enough, I went and updated my webpack.config.js (the entire config can be seen here) and Bootstrap then started working (the only change I did was to replace Tether with Popper):
plugins: [
new ProvidePlugin({
'Promise': 'bluebird',
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
Popper: 'popper.js'
}),
I also did the import 'bootstrap' in my main.ts file.
However I now have another problem (which I did not have with Tether), a new error is thrown in the console:
Uncaught TypeError: Popper is not a constructor
If I try to debug in Chrome, I do have Popper loaded as an Object (which is why Bootstrap stopped complaining) as you can see in the print screen below.
Finally to include all my code. I use Bootstrap tooltip with a simple custom element built with Aurelia and TypeScript (which used to work with previous Bootstrap alpha 6 and Tether)
import {inject, customAttribute} from 'aurelia-framework';
import * as $ from 'jquery';
#customAttribute('bootstrap-tooltip')
#inject(Element)
export class BootstrapTooltip {
element: HTMLElement;
constructor(element: HTMLElement) {
this.element = element;
}
bind() {
$(this.element).tooltip();
}
unbind() {
$(this.element).tooltip('dispose');
}
}
Looks like I did not import Popper correctly, if so then what is the best way to achieve that with Webpack 3.x?
While browsing Bootstrap 4 documentation. I actually found a section about Webpack which explains how to install it correctly. Following the Bootstrap - installing with Webpack documentation, the answer is to simply modify the webpack.config.js with the following:
plugins: [
// ...
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
})
// ...
]
and let's not forget to import it in the main.ts
import 'bootstrap';
and voilĂ ! We are back in business :)
If you are using Webpack Do this:
window.$ = window.jQuery = require('jquery');
window.Popper = require('popper.js').default; // pay attention to "default"
require('bootstrap/dist/js/bootstrap');
In bootstrap": "^4.1.1" no need to import jquery and popper.js because those plugins will be already included when 'bootstrap' or bootstrap's plugins imported individually.
Notice that if you chose to import plugins individually, you must also
install exports-loader
No need to require files require('exports-loader?file ... '); as mentioned here because this will be taken care automatically by just installing $ npm install exports-loader --save-dev
import 'bootstrap'; // Import all plugins at once
//
// Or, import plugins individually
//
// import 'bootstrap/js/src/alert';
// import 'bootstrap/js/src/button';
// import 'bootstrap/js/src/carousel';
// import 'bootstrap/js/src/collapse';
// import 'bootstrap/js/src/dropdown';
// import 'bootstrap/js/src/modal';
// import 'bootstrap/js/src/popover';
// import 'bootstrap/js/src/scrollspy';
// import 'bootstrap/js/src/tab';
// import 'bootstrap/js/src/tooltip';
// import 'bootstrap/js/src/util';
There is no need to do anything like below:
const webpack = require('webpack');
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
})
]
}
}
I am a vue.js developer and in new vue-cli-3, we create vue.config.js in root and place code like above to register new plugin, but as said there is no need to do all this in bootstrap": "^4.1.1".
Bootstrap's tooltip plugin is depend on popper.js and need to be enabled manually, so you can do like below in the component where you use tooltip element:
<script>
import $ from 'jquery';
export default {
mounted() {
$('[data-toggle="tooltip"]').tooltip();
},
};
</script>
I just ran into the same issue, and the solution is described here: https://github.com/FezVrasta/popper.js/issues/287
My main.ts now looks like something like the following:
import "jquery";
import Popper from "popper.js";
(<any>window).Popper = Popper;
require("bootstrap");
And I had to run npm install #types/requirejs --save to get the call to require working.
EDIT: I totally missed this the first time around, but the documention actually has a better way to solve this https://getbootstrap.com/docs/4.0/getting-started/webpack/
plugins: [
...
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default'],
// In case you imported plugins individually, you must also require them here:
Util: "exports-loader?Util!bootstrap/js/dist/util",
Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
...
})
...
]
In ASP.net Core 2 project add the following scripts to of main HTML file ("_Layout.cshtml" file)
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/js/popper.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
For me it's working.

Adding Colorbox to my ReactJS application creates "jQuery is not defined"

I'm trying to add Colorbox library to my project created with create-react-app. I've installed jquery-colorbox package via npm and added imports in one of my *.js files:
import $ from 'jquery'; // also tried: import jQuery from 'jquery';
import 'jquery-colorbox';
After that, all I'm getting is an error:
ReferenceError: jQuery is not defined
(anonymous function)
node_modules/jquery-colorbox/jquery.colorbox.js:1105
1102 |
1103 | publicMethod.settings = defaults;
1104 |
> 1105 | }(jQuery, document, window));
1106 |
1107 |
1108 |
Anyone have any suggestions how to manage with that problem?
Also, the code I want to run with the Colorbox library is something like this:
$(function() {
$('.colorbox-group' + id).colorbox({
rel: 'colorbox-group' + id,
maxWidth: '95%',
maxHeight: '95%'
});
});
UPDATE #1
Also... tried with CDN's and added these lines to index.html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js"></script>
And run code inside one of JS files of my app: $.colorbox('something');.
Result:
TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery___default.a.colorbox is not a function
Solution 1: Using cdn for jquery & jquery-colorbox
Here is a simple github repository, I have made using reactjs. Hope it helps!
Solution 2: Using npm packages for jquery & jquery-colorbox
Here is a github repository using npm packages with react setup. I have also had the same issue that you got for 'jQuery' undefined. The solution is in webpack config by adding a webpack plugin for jQuery. Add this in your webpack-config file:
On top first import the webpack:
let webpack = require('webpack');
and then add this code:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
Solution 3: specifically for 'create-react-app'
Update the import in your app.js file like below:
import jQuery from 'jquery';
window.jQuery = jQuery;
require('jquery-colorbox');
Hope it solves your query.
It looks like it is using the variable jQuery rather than $. I might try importing the jQuery object by its name, for example:
import {$, jQuery} from 'jquery';
or maybe just:
import jQuery from 'jquery';

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

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".

Using webpack to process an AMD library with external dependencies

I have a library written in AMD style that can be used with RequireJS. jquery and jquery-ui are assumed to be provided by the user of the library. Say it looks like this:
// main-lib.js
define(['jquery', './aux-lib.js'], function ($) { ..(1).. });
// aux-lib.js
define(['jquery', 'jquery-ui'], function ($) { ..(2).. });
I'm trying to figure out how webpack works. For example, say I want to bundle these files into a single AMD style library file that still assumes jquery and jquery-ui from the outside:
// out.js
define(['jquery', 'jquery-ui'], function ($) { ..(1)..(2).. } );
How is this accomplished?
When I run webpack with main-lib.js as entry-point, it will complain that it can't find jquery and jquery-ui. If I configure the correct paths with resolve.alias, it bundles jquery and jquery-ui into out.js, which is not what I want. I tried using output.externals to no avail.
This was a pretty simple, stupid mistake on my part. The relevant field is not output.externals, but simply externals. See here. The other two relevant fields introduced there are inside output, but externals is not.
PS: externals can also be an array. Here is my current configuration:
{
entry: './main-lib.js',
output: {
path: './',
filename: 'out.js',
libraryTarget: 'amd'
},
externals: ['jquery', 'jquery-ui']
}
It's working quite nicely.

Categories

Resources