4

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!

1
  • Are you by any chance using the minifed jQuery? This might be the issue. Commented Dec 30, 2015 at 7:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.