Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to load Bootstrap with an ES6 import?

Tags:

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.

like image 236
BishopZ Avatar asked May 26 '16 05:05

BishopZ


People also ask

Can I use ES6 imports?

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.

How do I add bootstrap to my project in Webpack?

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.


2 Answers

If you have 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 :

In the webpack configuration :

// webpack.config.js ... plugins: [   new webpack.ProvidePlugin({     jQuery: 'jquery',     $: 'jquery'   }) ] ... 

Now, in our 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.

like image 65
Aakash Avatar answered Sep 22 '22 17:09

Aakash


Bootstrap 4 Solution

Bootstrap 4 has two dependencies: jQuery and Popper.js.

  1. Install necessary packages:

    npm install jquery popper.js bootstrap --save 
  2. In your app, import like so:

    import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.css'; 
  3. 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'   }) ] 
like image 33
Michael Hays Avatar answered Sep 18 '22 17:09

Michael Hays