Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make jquery available to sprockets using Webpacker?

I've just started experimenting with Webpacker within an existing app.

From all that I've read, my understanding is that Webpacker and Sprockets can co-exist, and that libraries compiled in Webpacker (e.g., jquery) can be made available to Sprokets via global variables.

But all my jquery in the asset pipeline are raising ReferenceError: Can't find variable: $

Have I misunderstood, or is there a bug in my code?

I've added jquery

yarn add jquery

and assigned the variables in environment.js

const { environment } = require('@rails/webpacker');

const webpack = require('webpack');
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
}));

module.exports = environment;

this works:

#javascript/packs/application.js
$(function () {
    console.log('Hello World from Webpacker via JQUERY');
});

this does not

#assets/javascripts/application.js
$(function () {
    console.log('Hello World from Sprockets via JQUERY');
});
# ReferenceError: Can't find variable: $

What is the expected behaviour?

like image 664
Andy Harvey Avatar asked Aug 19 '18 18:08

Andy Harvey


1 Answers

In the end it is relatively easy to expose jQuery to global from within webpacker. But finding documentation on how to do this was very difficult! Hopefully, this can save someone else a search.

Add expose-loader

yarn add expose-loader -D

And then add the following configuration to config/webpack/environment.js

environment.loaders.append('expose', {
    test: require.resolve('jquery'),
    use: [{
        loader: 'expose-loader',
        options: '$'
    }, {
        loader: 'expose-loader',
        options: 'jQuery',
    }]
})

I was then able to remove jquery from the asset pipeline, restart the server, and all my remaining jquery functions within sprockets continue to function as expected.

like image 93
Andy Harvey Avatar answered Sep 24 '22 08:09

Andy Harvey