简体   繁体   中英

Error when using webpack with jQuery

I'm just starting to use Webpack, and I have an issue when I try to use jQuery with it. I'm a very newbie with Webpack, so please apologize if my question seems very basic.

Here is my webpack.config.js:

var webpack = require("webpack");
var path = require("path");
var bower_dir = __dirname + "/public/js/bower_components";
var compiled_dir = __dirname + "/public/js/compiled";

module.exports = {
    entry: {
        signup: compiled_dir + "/signup"
    },
    plugins: [
        new webpack.ProvidePlugin({
            $ : "jquery",
            jQuery : "jquery",
            "window.jQuery" : "jquery",
            "root.jQuery" : "jquery"
        })
    ],
    resolve: {
        alias: {
            jquery : bower_dir + "/jquery/src/jquery",
        }
    },
    output: {
        path: path.join(__dirname, "public/js/dist"),
        filename: "[name].bundle.js"
    }

};

As I'm using ProvidePlugin (for jQuery plugins), I have no require("jquery") at the begininng of my file. However, at execution, I get this output on the console :

TypeError: jQuery.expr is undefined http://localhost:9000/js/dist/signup.bundle.js Line 6250

Do you have any clue ?

Thanks in advance.

Solved by removing "resolve" section in webpack.config.js and by installing jquery with npm. However, if someone could explain me why it works now, I would be very grateful :-)

This seems to be an issue with an earlier/current version of JQuery, according to this issue raised here - https://github.com/webpack/webpack/issues/1066 .

To summarize from the above link, JQuery uses RequireJS, which has an implementation of AMD different from that of the actual AMD spec. This might be fixed in later versions. For now, try using the dist folder, which works just fine as well. Just change this line here -

alias: {
        jquery : bower_dir + "/jquery/src/jquery",
    }

to this -

alias: {
        jquery : bower_dir + "/jquery/dist/jquery",
    }

In the meantime, there is a Webpack loader to fix this, and also a tutorial on how to use it, by Alexander O'Mara -

https://github.com/AlexanderOMara/amd-define-factory-patcher-loader http://alexomara.com/blog/webpack-and-jquery-include-only-the-parts-you-need/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM