Search code examples
twitter-bootstrapgulpbootstrap-4browserify

How to require Bootstrap 4 dependencies (jQuery & Popper.js) using Browserify / Gulp


I am trying to create a boilerplate for my bootstrap 4 projects & am wanting to use Browserify to add Bootstrap 4 and it's dependencies (jQuery & Popper.js) to my script file however I am not entirely sure how to pull in the libraries.

I have installed all 3 to the node-modules using NPM & have added them to the dev dependencies section of package.json:

    "bootstrap": "^4.0.0",
    "gulp": "^3.9.1",
    "gulp-browserify": "^0.5.1",
    "gulp-concat": "^2.6.1",
    "gulp-util": "^3.0.8",
    "jquery": "^1.9.1",
    "popper.js": "^1.14.2"

I have also set up a gulp file which, in it's current iteration, merges my script files and calls gulp-broswserify:

// calls in required plugins
const GULP = require("gulp"),
      GUTIL = require("gulp-util"),
      CONCAT = require("gulp-concat")
      BROWSERIFY = require("gulp-browserify");

// pulls in component files to use in gulp functions
const JS_SOURCES = "components/scripts/*.js";

// concatinates js components into one file
GULP.task("js", function(){
  GULP.src(JS_SOURCES)
    .pipe(CONCAT("script.js"))
    .pipe(BROWSERIFY())
    .pipe(GULP.dest("builds/development/js"))
});

In the first of my script files I added the following code which I expected to add Bootstrap, jQuery & Popper to my script:

// imports bootstrap and dependencies
$ = require('jquery');
var popper = require('popper.js');
var bootstrap = require('bootstrap');

However when I run the gulp js task in the terminal I get this error:

events.js:160
      throw er; // Unhandled 'error' event
      ^
Error: module "jquery" not found from "/Users/user/Desktop/code/bootstrap-4-boilerplate/components/scripts/fake_e1b7cd70.js"
    at notFound (/Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browserify/index.js:803:15)
    at /Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browserify/index.js:754:23
    at /Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browser-resolve/index.js:185:24
    at /Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browser-resolve/node_modules/resolve/lib/async.js:44:14
    at process (/Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browser-resolve/node_modules/resolve/lib/async.js:113:43)
    at /Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browser-resolve/node_modules/resolve/lib/async.js:122:21
    at load (/Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browser-resolve/node_modules/resolve/lib/async.js:54:43)
    at /Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browser-resolve/node_modules/resolve/lib/async.js:60:22
    at /Users/user/Desktop/code/bootstrap-4-boilerplate/node_modules/browser-resolve/node_modules/resolve/lib/async.js:16:47
    at FSReqWrap.oncomplete (fs.js:123:15)

Can anybody show me where I am going wrong / direct me to an example of where someone has used Gulp & Browserify to load Bootsrap 4? It must be a common use case.

Thanks in advance.


Solution

  • You can use the snippet bellow, to bundle your .js files with gulp and browserify.

    import gulp from 'gulp'
    import gulpLoadPlugins from 'gulp-load-plugins'
    import browserify from 'browserify'
    import source from 'vinyl-source-stream'
    import buffer from 'vinyl-buffer'
    import log from 'gulplog'
    import babelify from 'babelify'
    
    const $ = gulpLoadPlugins()
    
    const src = `${__dirname}/app`
    const dist = `${__dirname}/dist`
    
    function bundle () {
      // Input file.
      const bundler = browserify(`${src}/scripts/main.js`, {
        debug: true
      })
    
      // Babel transform
      bundler.transform(babelify)
    
      return bundler.bundle()
        .on('error', log.error)
        .pipe(source('main.bundle.min.js'))
        .pipe(buffer())
        .pipe($.sourcemaps.init({ loadMaps: true }))
        .pipe($.if(process.env.NODE_ENV === 'production', $.uglify()))
        .pipe($.size({ title: 'scripts' }))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest(`${dist}/scripts`))
        .pipe(gulp.dest(`.tmp/scripts`))
    }
    
    gulp.task('lint', () => {
      return gulp.src([
        `${src}/scripts/**/*.js/`
      ])
        .pipe($.eslint())
        .pipe($.eslint.results(results => {
          // Called once for all ESLint results.
          console.log(`Total Results: ${results.length}`)
          console.log(`Total Warnings: ${results.warningCount}`)
          console.log(`Total Errors: ${results.errorCount}`)
        }))
        .pipe($.eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failAfterError last.
        // .pipe($.eslint.failAfterError())
    })
    
    gulp.task('scripts', ['lint'], () => bundle())

    For run that gulp task witch uses enviroments variables, you can put that scripts on your package.json

    "scripts": {
        "dev": "cross-env NODE_ENV=development gulp scripts",
        "prod": "cross-env NODE_ENV=production gulp scripts"
    }
    

    I am using cross-env, for cross platform working

    On your .js file you can have these imports:

    import $ from 'jquery'
    import 'popper.js'
    import 'bootstrap'
    
    // For some plugins and global use.
    window.jQuery = window.$ = $
    

    Its assume that you have those projects installeds under npm or yarn.