I'm having trouble figuring out the correct way to load third-party libraries that have dependencies on each other. I am using TypeScript and Gulp with either Webpack or SystemJS for my module loader, both of which are throwing similar errors in this situation. My application code runs smoothly with just jQuery, but as soon as I try to incorporate a jQuery plugin like jQuery Validation, I encounter issues with both Webpack and SystemJS indicating that jQuery is undefined.
There is quite a bit of configuration involved in both setups. Let me illustrate my most recent attempt with Webpack:
Here is my main.ts
file:
import * as $ from "jquery";
// if I comment out these two imports, the '$("body").css...' line works
import "../bower_components/jquery-validation/dist/jquery.validate";
import "../bower_components/jquery-validation-unobtrusive/jquery.validate.unobtrusive";
$("body").css("color", "red");
The gulpfile used to generate the output:
var gulp = require('gulp'),
webpack = require("gulp-webpack");
gulp.task("tsc-webpack", function () {
return gulp.src("app/main.ts")
.pipe(webpack({
output: {
filename: "main.js"
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: "ts-loader" }
]
}
}))
.pipe(gulp.dest(appDir + "js"))
});
My tsconfig.json file:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"module": "commonjs"
},
"exclude": [
"node_modules"
]
}
Here is the error I am encountering in the Chrome developer console:
Uncaught ReferenceError: jQuery is not defined
at Object.<anonymous> (main.js:12312)
at __webpack_require__ (main.js:20)
at Object.<anonymous> (main.js:51)
at __webpack_require__ (main.js:20)
at Object.defineProperty.value (main.js:40)
at main.js:43
And here is the block in the generated file that is causing the error (last line):
(function ($) {
var $jQval = $.validator,
// ...
$(function () {
$jQval.unobtrusive.parse(document);
});
}(jQuery));