1
votes

I have problem with jquery connection to my Project on the Phoenix Framework. I have installed jQuery through npm install

npm i jquery

I add import to app.js.

import $ from 'jquery'

My dependencies at package.json

"jquery": "^3.4.1",
"phoenix": "file:../deps/phoenix",
"phoenix_html": "file:../deps/phoenix_html"

But in console I have error

Uncaught ReferenceError: $ is not defined

My js

<script>
    $("#login-btn").click(function(){
        console.log("Sign in button pressed");
    });
</script>

Please, help me.

2

2 Answers

2
votes

You need to add this line to assets/webpack.config.js

const webpack = require('webpack');

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

and assets/js/app.js

import $ from 'jquery'
window.jQuery = $
window.$ = $
0
votes

When you import jQuery, it is only available in that module. It doesn't get automatically set on the window object, which is where it gets searched in that script tag.

I am not sure if it's a good practice, but in your specific case you can try to do something like:

import {$, jQuery} from 'jquery';

window.$ = $;
window.jQuery = jQuery;