Error using Bootstrap & jQuery Packages in ES6 with Browserify

£可爱£侵袭症+ 提交于 2019-12-03 16:29:22

问题


I'm trying to use Bootstrap with jQuery. I'm using Browserify with a Babel transform to compile. I get the following error.

Uncaught ReferenceError: jQuery is not defined

I've tried importing the packages like this, but I get the above error.

import $ from 'jquery';
import Bootstrap from 'bootstrap';

Searching around, I found this answer, so I tried this but I still get the same error.

import $ from 'jquery';
window.$ = window.jQuery = $;
import Bootstrap from 'bootstrap';
Bootstrap.$ = $;

Am I importing these packages incorrectly with ES6 or is it done in a different way? The last thing I tried was importing the packages without ES6 like this, but I still got the same error.

window.$ = window.jQuery = require('jquery');
var Bootstrap = require('bootstrap');
Bootstrap.$ = $

回答1:


The accepted answer helped me to right track but the final solution for me was a bit shorter so I will post also here.

// Importing jQuery in ES6 style
import $ from "jquery";

// We need to expose jQuery as global variable
window.jQuery = window.$ = $;

// ES6 import does not work it throws error: Missing jQuery 
// using Node.js style import works without problems
require('bootstrap');



回答2:


As mentioned by Pete TNT, there is a bug in the Bootstrap package I am using. I switched to using this Bootstrap package and made the following changes to my code.

window.$ = window.jQuery = require('jquery');
var Bootstrap = require('bootstrap-sass');
Bootstrap.$ = $;
require('../../../../../node_modules/bootstrap-sass/assets/javascripts/bootstrap');

It looks like, for the time-being, ES6 imports will not work with jquery and bootstrap packages in the way I was trying to use them.




回答3:


@Enijar's solution didn't work for me. Had to use old CDN method.

<script   src="https://code.jquery.com/jquery-3.1.0.min.js"   
integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   
crossorigin="anonymous"></script>

https://code.jquery.com/




回答4:


I've tried many many solutions but for some reason I had to define the global jquery in lowercase on the base script (eg. main.js)

import jQuery from 'jquery'
global.jQuery = jQuery
global.jquery = jQuery // jquery lowercase was the solution for me
global.$ = jQuery
let Bootstrap = require('bootstrap')
import 'bootstrap/dist/css/bootstrap.css'

This solutions also works for vue-cli + jquery + bootstrap



来源:https://stackoverflow.com/questions/34120250/error-using-bootstrap-jquery-packages-in-es6-with-browserify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!