Using Bootstrap 3.0 with Browserify

笑着哭i 提交于 2019-11-28 07:26:26
Ian Lim

This works for me when I'm using bootstrap in browserify:

window.$ = window.jQuery = require('jquery')
var Backbone = require('backbone');
Backbone.$ = $;
require('../../../../bower_components/bootstrap-sass-official/assets/javascripts/bootstrap');

I ran into the same problem: Bootstrap is available in NPM but is not exposed as a Common JS module. The approach I settled on was:

  1. Temporarily set window.$ and window.jQuery
  2. Load Bootstrap.js by requiring it
  3. Revert the value of window.$ and window.jQuery

I placed the code below into a module called bootstrapHack.js and required it at the root of my app before anything else runs.

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

require('bootstrap');

jQuery.noConflict(true);

Or if you're only working with one or two Bootstrap components, you can require them individually and cut down on the file size. In this case, just modal and tooltip.

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

require('bootstrap/js/tooltip');
require('bootstrap/js/modal');

jQuery.noConflict(true);

A cleaner approach would be to use the atomify plugin. That would help you resolve jQuery, bootstrap.js and bootstrap.css all from npm module.

var gulp = require('gulp');
var atomify = require('atomify');

gulp.task('default', function () {
  atomify.css('less/main.less', 'dist/bundle.css');
  atomify.js('js/index.js', 'dist/bundle.js');
});

You need to @import bootstrap in to your less / css file,

@import 'bootstrap';
@import './other.less';

@dark : #999;

body {
  background-color : @dark;
}

as well as require() bootstrap in your js file,

var $ = jQuery = require('jQuery')
require('bootstrap');
var other = require('./other')

console.log(typeof $().modal);
console.log(other());

module.exports = function() {
  console.log('Executed function xyz');
}

A complete example in this Github repo.

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