我似乎无法找到正确的方法来加载相互依赖的第三方库。我在我的模块加载程序中使用了TypeScript和Gulp以及Webpack或SystemJS,在本例中两者都有类似的错误。如果我只使用jQuery,我的应用程序代码就能工作,但是如果我尝试使用一个jQuery插件,比如jQuery验证,我会从Webpack和SystemJS那里得到类似的错误,说明jQuery是未定义的。
这两种设置都有很多配置,我将在这里演示我最近在Webpack的尝试:
我的main.ts文件:
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");用于生成输出的gulpfile:
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"))
});我的tsconfig.json文件:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"module": "commonjs"
},
"exclude": [
"node_modules"
]
}以下是我从控制台获得的错误
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下面是生成文件中抛出错误的块(在最后一行)
(function ($) {
var $jQval = $.validator,
// ...
$(function () {
$jQval.unobtrusive.parse(document);
});
}(jQuery));发布于 2017-05-04 14:16:28
对于webpack中的jquery,我通常使用:
module: {
rules: [
{ test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' },
]
},
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery'
}),
]Webpack应该能识别jquery-validation /commonjs,而define看起来就像是在检查define。
这里有更多关于shimming的信息:https://webpack.js.org/guides/shimming/
https://stackoverflow.com/questions/43785212
复制相似问题