I recently switched from using Require.js to using WebPack with Babel. In the past I would use the CommonJS standard in my JS modules, like this
var $ = require('jquery'); require('bootstrap');
Since Bootstrap is a jQuery plugin, jQuery would load first and bootstrap would load second.
Babel allows me to use ES6 import
statements. But when I write
import $ from 'jquery'; import Bootstrap from 'bootstrap';
I get the error that $ is undefined
. Bootstrap assumes that window.$
is present, but import
does not pollute the window object, which is a good thing, but leaves my code like this:
// legacy loading for bootstrap var $ = require('jquery'); window.$ = $; require('bootstrap'); // the rest of the imports import _ from 'underscore';
There must be a better solution. Any help appreciated.
Importing can be done in various ways:Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.
Importing JavaScriptimport 'bootstrap/js/dist/util'; import 'bootstrap/js/dist/dropdown'; ... Bootstrap is dependent on jQuery and Popper, these are defined as peerDependencies , this means that you will have to make sure to add both of them to your package. json using npm install --save jquery popper.
Webpack
in your build......you'll need to work with Webpack's provide plugin. Since the error is that jQuery is not defined
we will define/provide it with the plugin :
webpack configuration
:// webpack.config.js ... plugins: [ new webpack.ProvidePlugin({ jQuery: 'jquery', $: 'jquery' }) ] ...
ES6/2015 module
:// main.js ... // jquery is required for bootstrap import $ from 'jquery' // bootstrap import 'bootstrap' // bootstrap css import 'bootstrap/dist/css/bootstrap.css' ...
Reference : https://2017-sparkler.rhcloud.com/2017/02/01/bootstrap-in-webpack-es6-2015-project/
Good Luck.
Bootstrap 4 has two dependencies: jQuery and Popper.js.
Install necessary packages:
npm install jquery popper.js bootstrap --save
In your app, import like so:
import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.css';
If you want to use $
globally for jQuery, add this to your webpack config (this is webpack.base.conf.js
for me):
plugins: [ new webpack.ProvidePlugin({ $: 'jquery' }) ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With