Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add jquery third party plugin in rails 6 webpacker

I know its simple but with update of rails 6. there is new syntax in rails 6 for manage javascript assets which is maintained by webpacker.

//application.js
require("@rails/ujs") //.start()
require("turbolinks").start()
require("@rails/activestorage").start()
require('jquery').start()
require('jquery_ujs').start()
require('bootstrap-daterangepicker').start()
require("custom/custom").start()
require("bootstrap").start()
require("channels")

i am able to add custom/custom but bootstrap and jquery is not working i have install jquery and bootstrap via npm

like image 385
uzaif Avatar asked Feb 27 '19 12:02

uzaif


People also ask

Does rails come with jQuery?

This is a simple app that displays a list of tutorials saved in the database. Starting Rails 5.1, jQuery is not included by default.


2 Answers

run below command to add jQuery.

$ yarn add jquery

Add below code in config/webpack/environment.js

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

Require jquery in application.js file.

require('jquery')

No more need to add jquery-rails gem!

like image 148
Akash Rajput Avatar answered Sep 20 '22 23:09

Akash Rajput


to resolve jquery third party plugin issue add jquery via yarn

yarn add jquery

for adding jquery support in rails 6 application first we need to add below configuration

# app/config/webpack/environment.js
const {environment} = require('@rails/webpacker');

const webpack = require('webpack');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery' # or if its not work specify path `'jquery/src/jquery'` which node_modules path for jquery
}));

module.exports = environment;

for import any jquery related plugin in app/javascripts/packs/application.js

use below instructions

import 'bootstrap/dist/js/bootstrap';
import 'bootstrap-daterangepicker/daterangepicker'

updated with expose-loader for jQuery

yarn add expose-loader

Then add this to config/webpack/environment.js

   environment.loaders.append('jquery', {
      test: require.resolve('jquery'),
      use: [{
        loader: 'expose-loader',
        options: '$',
      }, {
        loader: 'expose-loader',
        options: 'jQuery',
      }],
    });
    module.exports = environment;
like image 30
uzaif Avatar answered Sep 23 '22 23:09

uzaif