Building a PWA on top of NodeJS. Utilizing gulp
to processes package/bundle
for production. Also using jQuery
.
Receiving the error:
Uncaught ReferenceError: jQuery is not defined
package.json
:
"devDependencies": {
"browserify": "^16.2.2",
"gulp": "^3.9.1",
"gulp-browserify": "^0.5.1",
"gulp-clean-css": "^3.10.0",
"gulp-concat-css": "^3.1.0",
"gulp-if": "^2.0.2",
"gulp-sourcemaps": "^2.6.4",
"gulp-uglify": "^3.0.1",
"gulp-webserver": "^0.9.1",
"jquery": "^3.3.1",
"sw-precache": "^5.2.1"
}
Gulp task is:
gulp.task('js', function () {
return gulp.src(src + '/js/app.js')
.pipe(browserify())
.pipe(gulpif(environment === 'production', uglify()))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(gulp.dest(dest + '/js'));
});
app.js
is:
(function () {
'use strict';
var $ = jQuery = require('jquery');
require('./bootstrap-3.3.7.min.js');
$('.loader').fadeOut(1000);
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js')
.then(function (registration)
console.log('Service Worker Active', registration.scope);
})
.catch(function (err) {
console.log('Service worker registration failed : ', err);
});
}
})(); // Page Ready
If my understanding of Node is correct, jQuery
gets included from the require
call before used the $
. So I am confused as to why I am receiving the error.
Note that while other posts have had issues with Browserify and jQUery, I do not believe that is the issue.
You are using use strict
, which prevents any miss creation of global variable.
Thus when issue is with var $ = jQuery = require('jquery');
as accidental variable jQuery which doesn't exist is been created as global variable and assigned to $
. use strict
prevented this.
Just use
'use strict';
var $ = require('jquery');
Also do read What does 'use strict' do in JavaScript