【问题标题】:Loading jQuery plugins with webpack, gulp, and typescript [duplicate]使用 webpack、gulp 和 typescript 加载 jQuery 插件
【发布时间】:2017-10-02 18:29:49
【问题描述】:

我似乎无法找到正确的方法来加载相互依赖的第三方库。我将 TypeScript 和 Gulp 与 Webpack 或 SystemJS 一起用于我的模块加载器,在这种情况下,两者都有类似的错误。如果我只使用 jQuery,我的应用程序代码可以工作,但如果我尝试使用 jQuery 插件,比如 jQuery Validation,我会从 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"
]
}

这是我从 Chrome 开发者控制台得到的错误

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));

【问题讨论】:

    标签: javascript jquery typescript webpack gulp


    【解决方案1】:

    我一般在 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 应该能够识别 amd/commonjs,而 jquery-validation 看起来像是在检查 define

    这里有更多关于匀场的信息:https://webpack.js.org/guides/shimming/

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 2018-06-20
      • 2018-04-01
      • 2019-03-31
      • 2017-12-09
      • 2016-11-03
      相关资源
      最近更新 更多