简体   繁体   中英

Gulp and Browserify, dependency management with Node.js require();. Put jQuery on top?

I don't think this question is a duplicate, because jquery doesn't need to be shimmed anymore. I downloaded jquery with npm as all other plugins I am using. I might be mistaken but I don't think it is the same situation as the other question.

Browserify gulp task (called as a module):

var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');

module.exports = function(gulp, plugins, config) {
  return function() {
    var b = browserify({
      entries: config.srcAssets + '/js/app.js',
      debug: true
    });

    return b.bundle()
      .pipe(source('bundle.js'))
      .pipe(buffer())
      .pipe(plugins.sourcemaps.init({
        loadMaps: true
      }))
      .on('error', gutil.log)
      .pipe(plugins.sourcemaps.write('./'))
      .pipe(gulp.dest(config.dest + '/js'));
  };
};

I simplified my files to the maximum to explain my problem.

app.js :

var form = require('./form');

form.js :

var $ = require('../../../config/node_modules/jquery');
var validator = require('../../../config/node_modules/jquery-validation');
$("#form").validate();
$(function() {
  $('.printArea').height($('#form').height());
})

It doesn't work, because the jquery validation plugin will always be above jquery in the bundle.js file. If I don't require the validation plugin and remove the js which depends on it (so only leaving my own jquery manipulations), it works.

I think the problem you're having with jquery-validation is that the NPM package is just the source; you still have to build a copy of the distributed file in order to use it, or pull it from Bower or a CDN. It isn't an NPM lib that can be included with Browserify. You will still need some kind of transform to package the built copy of jquery-validation for use in your app.

Here is how this problem was solved :

in package.json :

  "browser": {
    "jquery-validate" :  "./node_modules/jquery-validation/dist/jquery.validate.js"
  },
  "browserify": {
    "transform": [
      "browserify-shim"
    ]
  },
  "browserify-shim": {
    "jquery-validate" :  {
      "depends" :  [
      "jQuery"
      ]
    }
  }

in form.js :

$ = jQuery = require('../../../config/node_modules/jquery');
require('../../../config/node_modules/jquery-validation/dist/jquery.validate.js');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM