jquery plugin in backbone + browserify - javascript

The project I'm working on consisted of Backbone and browserify.
I've only worked with jquery and some of javascript.
This is the first project working with Backbone and browserify framworks.
The problem is whenever trying to use jquery plugin something is not working.
Reason why I use jquery plugin is understandable for me.
in package.json
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.min.js",
"bootstrap": "./src/javascript/vendor/bootstrap.min.js",
"masonry": "./src/javascript/vendor/masonry.pkgd.min.js",
"removeClassPrefix": "./src/javascript/vendor/jquery-removeClassPrefix.js",
"jquery-validate": "./src/javascript/vendor/jquery.validate.min.js"
},
"browserify": {
"transform": [
"browserify-shim",
"coffeeify",
"hbsfy"
]
},
"browserify-shim": {
"jquery": "$",
"bootstrap": {
"exports": "bootstrap",
"depends": [
"jquery:$"
]
},
"masonry": {
"exports": "masonry",
"depends": [
"jquery"
]
},
"removeClassPrefix": {
"exports": "removeClassPrefix",
"depends": [
"jquery:$"
]
},
"jquery-validate": {
"exports": "jquery-validate",
"depends": [
"jquery:$"
]
}
},
and actual code written in coffeescript
_ = require 'underscore'
Backbone = require 'backbone'
$ = require 'jquery'
Backbone.$ = $
Backbone.Marionette = require 'backbone.marionette'
ModalModel = require '../models/modalModel'
jquery-validate = require 'jquery-validate'
module.exports = Backbone.Marionette.ItemView.extend
After building codes, an error occurred on the first line of the code above.
Uncaught ReferenceError: jquery is not defined
without code below everything works fine.
jquery-validate = require 'jquery-validate'
That means there is something quite not working in the jquery plugin(jquery-validate)
jquery-validate is expending jquery function I guess.
Is there any way I can solve this issue?

You can't use dashes in a valid JavaScript variable identifier, so try changing jquery-validate = require 'jquery-validate' to jquery_validate = require 'jquery-validate'.

Related

How do I properly separate my app.js and vendor.js bundles using Browserify?

My goals are to include the following in my HTML file and have them all work properly:
index.html:
<script type="text/javascript" src="./vendor.js"></script>
<script type="text/javascript" src="./app.js"></script>
$(document).ready(function() {
// jQuery should be available as `window.$`
$(".myclass").doSomethingWithJquery();
}
<div class="row">
<h1 class="col-md-3 col-md-offset-3">
I should be able to use bootstrap, including bootstrap's javascript libraries, in my templates
</h1>
</div>
<!-- I should be able to use app.js, with its various require('module')
statements and attach rendered HTML to the DOM (I'm using React) -->
<div id="attach-app-js"></div>
Therefore:
jQuery should be available as a global $ variable.
Bootstrap's javascript functions should also work, as they're part of vendor.js
My app.js should also work and not re-declare variables like $ that is already declared under global scope via vendor.js.
See the files below. My current solution errors where I have $(".myclass").doSomethingWithJquery(); When my internet is off, I get the error:
Uncaught ReferenceError: $ is not defined
...which makes me think that (maybe) snackbarjs or another module is leaking jQuery to global scope.
Then, when I change the line in vendor.js to: var $ = jQuery = require('jquery'); I get the error:
Uncaught ReferenceError: $ is not defined
but now it's getting called on the line $(document).ready(function.....
Third, if I comment out vendor.js entirely, I get both errors:
Uncaught ReferenceError: $ is not defined
Uncaught ReferenceError: jQuery is not defined
How can I get this frontend setup to correctly shim variables when necessary in the global scope, and not if it's not necessary??
gulpfile.js:
.task('vendor', ['clean'], function() {
var b = browserify(package.paths.vendor);
var packages = getBowerPackageIds();
packages.forEach(function (id) {
var resolvedPath = bowerResolve.fastReadSync(id);
b.require(resolvedPath, {
// exposes the package id, so that we can require() from our code.
// for eg:
// require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular');
// for more information: https://github.com/substack/node-browserify#brequirefile-opts
expose: id
});
});
return b
.bundle()
.pipe(source(package.dest.vendor))
.pipe(gulp.dest(package.dest.dist));
})
.task('js', ['clean', 'install'], function() {
var b = browserify(package.paths.app);
// mark vendor libraries defined in bower.json as an external library,
// so that it does not get bundled with app.js.
// instead, we will load vendor libraries from vendor.js bundle
getBowerPackageIds().forEach(function (lib) {
b.external(lib);
});
var w = watchify(b, watchify.args);
var file = package.dest.app,
dest = package.dest.dist;
w = w
.transform(reactify)
.transform(browserifyShim);
w.on('update', rebundle);
function rebundle() {
return w.
bundle()
.on('error', errorHandler)
.pipe(source(file))
.pipe(gulp.dest(dest))
.pipe(shell([
'python manage.py collectstatic --noinput'
], {
cwd: '../'
}))
// TODO: Do I need this?
.pipe(browserSync.reload({stream: true}));
}
return rebundle();
})
/**
* Running livereload server
*/
.task('server', ['clean', 'install', 'vendor', 'js', 'less'], function() {
browserSync({
proxy: "localhost:8000"
});
})
/**
* Compiling resources and serving application
*/
.task('serve', ['install', 'backup', 'clean', 'lint', 'less', 'vendor', 'js', 'server'], function() {
return gulp.watch([
package.paths.js,
package.paths.app,
package.paths.html,
package.paths.less,
package.paths.python
], [
'lint', 'less', browserSync.reload
]);
})
vendor.js:
$ = jQuery = require('jquery');
require('bootstrap');
require('snackbarjs');
package.json (browserify-shim config):
"browserify-shim": {
"jquery": "$",
"bootstrap": {
"depends": [
"jquery:jQuery"
],
"exports": "bootstrap"
},
"jquery-cookie": {
"depends": [
"jquery:jQuery"
]
},
"eonasdan-bootstrap-datetimepicker": {
"depends": [
"jquery:jQuery",
"moment:moment",
"bootstrap:bootstrap"
],
"exports": "$.fn.datetimepicker"
},
"image-picker": {
"depends": [
"jquery:jQuery"
],
"exports": "$.fn.imagepicker"
},
"raven-js": {
"depends": [
"jquery:jQuery"
],
"exports": "raven-js"
},
"parsleyjs": {
"depends": [
"jquery:jQuery"
],
"exports": "parsleyjs"
}
},
"browser": {
"jquery": "./bower_components/jquery/dist/jquery.js",
"jquery-cookie": "./bower_components/jquery-cookie/jquery.cookie.js",
"image-picker": "./bower_components/image-picker/image-picker/image-picker.js",
"eonasdan-bootstrap-datetimepicker": "./bower_components/eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker.js",
"moment": "./bower_components/moment/moment.js",
"bootstrap": "./bower_components/bootstrap/dist/js/bootstrap.js",
"raven-js": "./bower_components/raven-js/dist/raven.js",
"parsleyjs": "./bower_components/parsleyjs/dist/parsley.js"
},

Loading javascript plugs in order with gulp / browserify

Soooooo.... I'm have a helluva time trying to figure out browserify.
Here's my app.js file:
var $ = require('../lib/jquery');
var foundation = require('../lib/foundation/foundation');
$(document).ready(function($){
$(document).foundation();
});
when i try loading the browserified file, I get this error:
Uncaught ReferenceError: jQuery is not defined
I'm using the latest version of jquery. Any idea what's going on?
so uh, i solved the problem by using browserify-shim
here's what i added to my package.json file:
"browser": {
"jquery": "./js/lib/jquery.js"
},
"browserify-shim": {
"jquery": "$"
},
"browserify": {
"transform": [ "browserify-shim" ]
},
"dependencies": {
"browserify-shim": "~3.2.0"
}
ta da

Uncaught ReferenceError: _ is not defined with Browserify

I have a Backbone project that requires a fair amount of shimming for browserify.
I have set it up so that all of my underscore files are concat'd into one file templates.js
In turn I have to shim this into my project:
package.json
"dependencies": {
.....
"underscore": "^1.7.0"
.....
}
......
"browserify": {
"transform": [
"browserify-shim"
]
},
"browser": {
"//": "SP Core Components",
"jst": "./jst/templates",
},
"browserify-shim": {
"jst" : {"depends": "underscore"}
}
.....
init.js
var JST = require('jst');
var jsonobject = {};
JST.staffOverview(jsonobject)
This will generate the following when trying to call :
Uncaught ReferenceError: _ is not defined
So my question is, how can I set underscore as a dependency of jst

Can't load Bootstrap with RequireJS

I can't seem to figure out how to load Bootstrap via RequireJS. None of the examples that I found worked for me.
Here is my shim:
require.config({
// Sets the js folder as the base directory for all future relative paths
baseUrl: "./js",
urlArgs: "bust=" + (new Date()).getTime(),
waitSeconds: 200,
// 3rd party script alias names (Easier to type "jquery" than "libss/jquery, etc")
// probably a good idea to keep version numbers in the file names for updates checking
paths: {
// Core libsraries
// --------------
"jquery": "libs/jquery",
"underscore": "libs/lodash",
"backbone": "libs/backbone",
"marionette": "libs/backbone.marionette",
// Plugins
// -------
"bootstrap": "libs/plugins/bootstrap",
"text": "libs/plugins/text",
"responsiveSlides": "libs/plugins/responsiveslides.min",
'googlemaps': 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDdqRFLz6trV6FkyjTuEm2k-Q2-MjZOByM&sensor=false',
// Application Folders
// -------------------
"collections": "app/collections",
"models": "app/models",
"routers": "app/routers",
"templates": "app/templates",
"views": "app/views",
"layouts": "app/layouts",
"configs": "app/config"
},
// Sets the configuration for your third party scripts that are not AMD compatible
shim: {
"responsiveSlides": ["jquery"],
"bootstrap": ["jquery"],
"backbone": {
// Depends on underscore/lodash and jQuery
"deps": ["underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Backbone"
},
"marionette": {
// Depends on underscore/lodash and jQuery
"deps": ["backbone", "underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Marionette"
},
'googlemaps': { 'exports': 'GoogleMaps' },
// Backbone.validateAll plugin that depends on Backbone
"backbone.validate": ["backbone"]
},
enforceDefine: true
});
and here is how I call Bootstrap:
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
'bootstrap',
],
function($, _, Backbone, Marionette, Navigations, Bootstrap){
The error that I get is this:
Uncaught Error: No define call for bootstrap
Any ideas on how to get this resolved?
I found a working example here:
https://github.com/sudo-cm/requirejs-bootstrap-demo
I followed it to get my code to work.
According to that demo, especially app.js, you simply make a shim to catch Bootstrap's dependency on jQuery,
requirejs.config({
// pathsオプションの設定。"module/name": "path"を指定します。拡張子(.js)は指定しません。
paths: {
"jquery": "lib/jquery-1.8.3.min",
"jquery.bootstrap": "lib/bootstrap.min"
},
// shimオプションの設定。モジュール間の依存関係を定義します。
shim: {
"jquery.bootstrap": {
// jQueryに依存するのでpathsで設定した"module/name"を指定します。
deps: ["jquery"]
}
}
});
and then mark Bootstrap as a dependency of the app itself, so that it loads before app.js.
// require(["module/name", ...], function(params){ ... });
require(["jquery", "jquery.bootstrap"], function ($) {
$('#myModalButton').show();
});
Finally, since app.js is the data-main,
<script type="text/javascript" src="./assets/js/require.min.js" data-main="./assets/js/app.js"></script>
Bootstrap's JS is guaranteed to load before any application code.
Bootstrap lib does not return any object like jQuery, Underscore or Backbone: this script just modifies the jQuery object with the addition of new methods. So, if you want to use the Bootstrap library, you just have to add in the modules and use the jquery method as usual (without declarating Bootstrap like param, because the value is undefined):
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
"bootstrap",
],
function($,_,Backbone,Marionette,Navigations){
$("#blabla").modal("show"); //Show a modal using Bootstrap, for instance
});
I found it was sufficient to add the following to my requirejs.config call (pseudocode):
requirejs.config({
...
shim: {
'bootstrap': {
deps: ['jquery']
}
}
});
I like to use Require.Js ORDER plugin, what it does? Simply loads all your Libraries in order, in this case you won't get any errors, ohh and bootstrap depends on jQuery, so we need to use shim in this case:
requirejs.config({
baseUrl: "./assets",
paths: {
order: '//requirejs.org/docs/release/1.0.5/minified/order',
jquery: 'http://code.jquery.com/jquery-2.1.0.min',
bootstrap: '//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min'
},
shim: {
'bootstrap': {
deps:['jquery']
}
}
});
require(['order!jquery', 'order!bootstrap'], function($) {
});

How to stop require.js one file optimization from minimizing some paths?

I'm using r.js to create a one file script for my application using the following command:
r.js -o ./scripts/require.build.json baseUrl=public/js/ name=main out=main.min.js
were require.build.json has the following options:
{
"paths": {
"jquery": "plugins/jquery.1.8.2.min",
"underscore": "plugins/underscore.1.4.2.min",
"backbone": "plugins/backbone.0.9.2.min"
},
"shim": {
"backbone": {
"deps": ["jquery", "underscore"],
"exports": "Backbone"
},
"underscore": {
"exports": "_"
}
}
}
my main file is just a simple test case:
/*jslint browser: true */
/*global define: false*/
define(function (require) {
"use strict";
var $ = require("jquery"),
Backbone = require("backbone");
window.console.log($);
window.console.log(Backbone);
});
I wonder, how can I avoid r.js from minifying the already minified files of my dependencies (jQuery, Underscore and Backbone) to save time?

Categories

Resources