0

There are good official phoenix docs explaining how to add an npm dependency (even uses jquery). Evidently, I am missing something here. Here is what I have:

Using elixir 1.6, phoenix 1.3, and node 8.9 on Mac OSX.

assets/js/app.js contains:

import $ from 'jquery';

assets/brunch-config.js contains:

 npm: {
    enabled: true,
    npm: {
      globals: {
        $: 'jquery',
        jQuery: 'jquery'
      }
    }
  }

package.json contains:

 "dependencies": {
    "jquery": "^3.3.1",
    "phoenix": "file:../deps/phoenix",
    "phoenix_html": "file:../deps/phoenix_html"
  }

My "application logic" - in a js file imported from assets/js/app.js:

$(function () {
  alert('Hello');
});

Do have a workaround by simply (manually) copying jquery.min.js from assets/node_modules/query/dist into assets/vendor. But am keen to understand what is going wrong with the automatic inclusion using npm and brunch asset pipeline.

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
arcseldon
  • 35,523
  • 17
  • 121
  • 125
  • 1
    And what's the problem? Do you get some error? – Dogbert Jan 28 '18 at 12:46
  • Are you loading the generated `public/app.js` file in your views? Example: https://github.com/phoenix-examples/hello_phoenix/blob/master/web/templates/layout/app.html.eex – Nate-Wilkins Jan 28 '18 at 14:23
  • Yes, I am - as above, the jquery function etc all loads into browser. $ is not recognised unless i also add jquery.mins.js to vendor. Otherwise app.js is loading as expected. – arcseldon Jan 28 '18 at 22:04
  • @Dogbert - the problem is that $ is not recognised. It seems that doing the above (as per official phoenix docs) still isn't enough to successfully load jquery (and find $ on window object (global). – arcseldon Jan 28 '18 at 22:05
  • Do hesitate to rebuke official docs so apologies in advance if there is some kind of oversight on my part. Hoping I just overlooked something. – arcseldon Jan 28 '18 at 22:07
  • Anyone have a working sample on github using NPM and jquery dependency? Be interested to do a comparison. – arcseldon Jan 28 '18 at 22:08
  • Can you try adding `import $ from 'jquery';` to the file which uses `$`? – Dogbert Jan 30 '18 at 05:45
  • @Dogbert - fyi only - this is the github repo - https://github.com/auth0-samples/auth0-elixir-single-page-app – arcseldon Jan 30 '18 at 09:34
  • Shall try your suggestion. – arcseldon Jan 30 '18 at 09:34

1 Answers1

0

You don't need import $ from 'jquery'; in app.js

In assets/brunch-config.js do this instead:

npm: {
  enabled: true,
  globals: {
    $: 'jquery',
    jQuery: 'jquery'
  }
}

(you have extra npm section inside top npm section)

I've answered similar question before, still actual: https://stackoverflow.com/a/43265955/1173020

denis.peplin
  • 9,585
  • 3
  • 48
  • 55