user1775651
user1775651

Reputation: 41

Using jQuery with Webpack

I'm migrating from RequireJS to Webpack and I'm having some trouble when requiring jQuery for my modules.

I know there are some answers about this and I've gone through them but I can't get it to work. This one: Managing Jquery plugin dependency in webpack is the one I've been reading.

My webpack.config.js looks like this:

var webpack = require("webpack");
var bower_dir = __dirname + '/bower_components';

var config = {
    addVendor: function(name, path) {
        this.resolve.alias[name] = path;
        //this.module.noParse.push(new RegExp(path));
    },
    entry: {
        app: ['./app/js/main.js'],
        vendors: ['jquery', 'bootstrap']
    },
    resolve: { alias: {} },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jquery": "jquery"
        })
    ],
    output: {
        path: './build',
        filename: 'bundle.js'
    },
    module: {
        noParse: [bower_dir + '/bootstrap/dist/js/bootstrap.min.js'],
        loaders: []
    }
};

config.addVendor('jquery', bower_dir + '/jquery/jquery.js');
config.addVendor('bootstrap', bower_dir + '/bootstrap/dist/js/bootstrap.min.js');

module.exports = config;

I'm using ProvidePlugin to require jQuery on every module that uses it. Also, I'm putting vendor libraries in a vendors.js file and my modules in main.js.

My main.js file has this few lines of code just to test if $ resolves to jQuery:

$(".search-toggle").on("click", function(e) {
    e.preventDefault();
    $(".search-container").toggle();
});

And my index.html has these lines in :

<script src="<s:url  value="/resources/build/vendors.js"/>"></script>
<script src="<s:url  value="/resources/build/bundle.js"/>"></script>

When I run my app I get Uncaught TypeError: $ is not a function in the console even though $ is in the global scope.

I'd really appreciate if you could give me a hand with this because I've been writing and rewriting my code and getting nowhere.

Thank you very much in advance!

Upvotes: 4

Views: 2247

Answers (1)

Shu Ding
Shu Ding

Reputation: 1675

Instead of webpack.ProvidePlugin, you could just use https://github.com/webpack/expose-loader:
loaders: [{ test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery', }]

Upvotes: 1

Related Questions