How to make j query work with phoenix framework

Uncaught ReferenceError: $ is not defined
app.js file
const $ = require(‘jquery’);

// Import local files
//
// Local files can be imported directly using relative paths, for example:
window.jquery = $;
window.$ = $;

If you are using webpack, you can add the following to your webpack.config.js file.

module.exports = (env, options) => ({
  ...
  plugins: [
    ...
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ]
})

If you are still using brunch, you can do something like the following in your brunch-config.js file.

exports.config = {
  ...
  npm: {
    globals: {
      $: 'jquery',
      jQuery: 'jquery'
    }
  }
}

If you are using something else, you will need to tell us how you are bundling your assets.

You can find the documentation for the webpack plugin here. And the brunch method here.

1 Like

First you need to install jquery on your project:
cd assets && npm install jquery

After that you have to add it on webpack config:

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

And finally you can add jquery on the app.js:

import jQuery from 'jquery';
window.jQuery = jQuery;
window.$ = jQuery;
1 Like