Joel Hoelting
Joel Hoelting

Reputation: 1992

Including jQuery in a Rails + Webpack Application

I'm having some trouble getting jQuery up and running in my rails application with Webpack. I'm currently migrating away from the rails asset pipeline. I removed all instances of the jquery ruby gem and rebundled. I've added jquery to my package.json file:

{
  "dependencies": {
    "jquery": "^3.2.1"
  }
}

Then I created a new webpack plugin:

const webpack = require('webpack')
const merge = require('webpack-merge')
const CompressionPlugin = require('compression-webpack-plugin')
const sharedConfig = require('./shared.js')

module.exports = merge(sharedConfig, {
  output: { filename: '[name]-[chunkhash].js' },
  devtool: 'source-map',
  stats: 'normal',

  plugins: [
    new webpack.providePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    }),

    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      sourceMap: true,

      compress: {
        warnings: false
      },

      output: {
        comments: false
      }
    }),

    new CompressionPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.(js|css|html|json|ico|svg|eot|otf|ttf)$/
    })
  ]
})

And then I required jquery in application.js

import 'jquery';

console.log('Hello World')

require('script')

Are there any other configuration steps that I am missing? I'm not sure why it's so difficult to include jQuery into rails/webpack, I haven't been able to find good documentation on accomplishing this.

Upvotes: 1

Views: 364

Answers (1)

fatfrog
fatfrog

Reputation: 2160

Instead of this

$: 'jquery',
jQuery: 'jquery'

Try this:

$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'

Upvotes: 1

Related Questions