Uncaught ReferenceError: _ is not defined with Browserify - javascript

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

Related

Require not working the way I thought it would

So I have the following gulp task:
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require("babelify");
gulp.task('make:flare-currency', function() {
return browserify({entries: [
'src/add-new-currency/flare-currency.js',
'src/add-new-currency/currencies/set_up_currencies.js'
]})
.transform(babelify)
.bundle()
.pipe(source('Flare-Currency.js'))
.pipe(gulp.dest('dist/flare/currency/'));
});
I have the following package.json:
{
"name": "flare-collection",
"description": "collection of scripts for the RPG Maker MV system.",
"version": "0.0.1",
"dependencies": {
"gulp": "3.9.0",
"browserify": "11.2.0",
"vinyl-source-stream": "1.1.0",
"babelify": "6.4.0",
"underscore.string": "2.3.0"
}
}
When I try to do, inside: src/add_new_currencies/flare_currency.js
var UnderScoreString = require('underscore.string/string');
I get:
Error: Cannot find module 'underscore.string/string' from
'/Users/AdamBalan/Documents/Flare-Collection/src/add_new_currencies'
All of my require statements require that I do: var bla = require('some/file/to/include.js')
All of my classes (I am using es6) have, at the bottom of the file: module.exports = ClassName;
Why am I getting this error?
More importantly, why do I have to include the path to the js file?
underscore.string don't have a string submodule (function). If You want load all packages try _s = require('underscore.string'). If You want load single module like slugify try slugify = require('underscore.string/slugify').
You don't need to include the path to the js file. If you select the directory, then node.js try to find index.js file.

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

jquery plugin in backbone + browserify

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'.

Browserify with twitter bootstrap

There are many similar questions including answers here on stack overflow, but none of them have worked for me, so here I am asking you guys. I appreciate everyone's time.
I recently started using gulp with browserify, and that works great.
I then tried to use browserify for the front-end using: Backbone and Bootstrap3.
things are appearing to work, until I try to require the js file that comes with Bootstrap. I get an error in my chrome tools stating: jQuery is undefined.
I have attempted to shim it in, but I am very confused by the shim. I am using jQuery 2.1.1, so I should not need to shim jQuery, but it exists in the shim now, as I was desperate and trying everything. Here is my package.json and my main.js file:
--------------package.json------------------
{
"name": "gulp-backbone",
"version": "0.0.0",
"description": "Gulp Backbone Bootstrap",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Rob Luton",
"license": "ISC",
"devDependencies": {
"jquery": "^2.1.1",
"backbone": "^1.1.2",
"browserify": "^4.2.1",
"gulp": "^3.8.6",
"vinyl-source-stream": "^0.1.1",
"gulp-sass": "^0.7.2",
"gulp-connect": "^2.0.6",
"bootstrap-sass": "^3.2.0",
"browserify-shim": "^3.6.0"
},
"browser": {
"bootstrap": "./node_modules/bootstrap-sass/assets/javascripts/bootstrap.js",
"jQuery": "./node_modules/jquery/dist/jquery.min.js"
},
"browserify": {
"transform": ["browserify-shim"]
},
"browserify-shim": {
"jquery": "global:jQuery",
"bootstrap": {
"depends": [
"jQuery"
]
}
}
}
------------------------- main.js ----------------------
var shim = require('browserify-shim');
$ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var bootstrap = require('bootstrap');
/* the following logs fine if I comment out the bootstrap require, otherwise I get 'jQuery undefined' */
console.log(Backbone);
$(function() {
alert('jquery works');
});
You shouldn't need to shim jquery that way if you've installed it with npm. The following works for a project I've been writing:
I've also learned that using npm for bootstrap is kind of a PITA. I've been using bower to install and maintain certain front-end components when they need to be shimmed like this.
package.json:
{
"name": "...",
"version": "0.0.1",
"description": "...",
"repository": {
"type": "git",
"url": "..."
},
"browser": {
"d3js": "./bower_components/d3/d3.min.js",
"select2": "./bower_components/select2/select2.min.js",
"nvd3js": "./bower_components/nvd3/nv.d3.min.js",
"bootstrap": "./node_modules/bootstrap/dist/js/bootstrap.js"
},
"browserify": {
"transform": [
"browserify-shim",
"hbsfy"
]
},
"browserify-shim": {
"d3js": {
"exports": "d3",
"depends": [
"jquery:$"
]
},
"bootstrap": {
"depends": [
"jquery:jQuery"
]
},
"select2": {
"exports": null,
"depends": [
"jquery:$"
]
},
"nvd3js": {
"exports": "nv",
"depends": [
"jquery:$",
"d3js:d3"
]
}
},
"devDependencies": {
"browserify-shim": "~3.4.1",
"browserify": "~3.36.0",
"coffeeify": "~0.6.0",
"connect": "~2.14.3",
"gulp-changed": "~0.3.0",
"gulp-imagemin": "~0.1.5",
"gulp-notify": "~1.2.4",
"gulp-open": "~0.2.8",
"gulp": "~3.6.0",
"hbsfy": "~1.3.2",
"vinyl-source-stream": "~0.1.1",
"gulp-less": "~1.2.3",
"bower": "~1.3.3",
"cssify": "~0.5.1",
"gulp-awspublish": "0.0.16",
"gulp-util": "~2.2.14",
"gulp-rename": "~1.2.0",
"gulp-s3": "git+ssh://git#github.com/nkostelnik/gulp-s3.git",
"gulp-clean": "~0.2.4",
"process": "~0.7.0"
},
"dependencies": {
"backbone": "~1.1.2",
"jquery": "~2.1.0",
"lodash": "~2.4.1",
"d3": "~3.4.8",
"rickshaw": "~1.4.6",
"datejs": "~1.0.0-beta",
"moment": "~2.7.0"
}
}
js:
$ = jQuery = require('jquery');
var _ = require('lodash');
var Rickshaw = require('rickshaw');
var d3 = require('d3js');
var nvd3 = require('nvd3js');
var moment = require('moment');
require('datejs');
require('select2');
var bootstrap = require('bootstrap');
console.log(bootstrap)
Also - one sometimes useful thing is to have browserify-shim output its diagnostics. This is what my browserify.js task looks like:
var browserify = require('browserify');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var process = require('process');
process.env.BROWSERIFYSHIM_DIAGNOSTICS=1;
var hbsfy = require('hbsfy').configure({
extensions: ['html']
});
gulp.task('browserify', ['images', 'less'], function(){
return browserify({
transform: ['hbsfy', 'cssify'],
entries: ['./src/javascript/app.js'],
})
.bundle({debug: true})
.on('error', handleErrors)
.pipe(source('app.js'))
.pipe(gulp.dest('./build/'));
});
There is error as I am using browserify which require the variable '$' or 'jQuery' to be defined.
adding the window to make it global resolve the error. Not sure if this would be the correct way to do, if not, let me know.
window.$ = window.jQuery = require('jquery');
var bootstrapjs = require('bootstrap-sass');
I've been wondering about this for a while. This simple solution does the job for me:
import foo from 'foo';
import bar from './bar';
import { default as $ } from "jquery";
global.$ = $;
global.jQuery = $; // This one does the trick for bootstrap!
// Boostrap's jQuery dependency only works with require, not with ES6 import!
const btp = require('bootstrap');
So to make Bootstrap to work with Browserify you're going to need one of Browserify CSS transforms.
First the index.js (browserify entry)
// Bootstrap needs jQuery on the Window
window.jQuery = $ = require('jquery');
// include popper.js if you want Bootstrap tooltips
window.Popper = require('popper.js');
// include bootstrap js libs (not the CSS libs as yet)
require('bootstrap');
// then the CSS Lib
require('bootstrap/dist/css/bootstrap.css');
NPM Installs:
npm install bootstrap#4.0.0-alpha.6 jquery popper.js
To use tooltips globally:
Per the Bootstrap docs.
$('[data-toggle="popover"]').popover();
I have a Browserify-Budo repo here. If you want to see it working.

Categories

Resources