Search code examples
javascriptjquerynode.jsnode-webkit

jquery not working well on node-webkit


I am practicing node-webkit as a nodejs beginner.
My main page is a simple html page including a main.js script

I've installed jquery using npm install jquery

index.html

<!-- index.html -->
...
<script src="js/main.js"></script>
</head>
<body>
<div id="demo">Hi! </div>
</body>
</html>

main.js

// main.js
const $ = require('jquery')

$(document).ready(function () {
  $('#demo').click(function () {
    $(this).text($(this).text() + 'Hi! ')
  })
})

If I load jquery in my index.html like <script src="path/to/jquery.js"></script> it works well, but if I require jquery in my main.js it doesn't!

I've already tested:

  • main.js is properly including and working with native js methods (like document.getElementById('demo').onclick = ...)
  • Other node modules or libraries such as vue, lodash or natives like fs, url work well. So require function works good.
  • While I'm requiring jquery as above, inline <script>s doesn't work as well.

Also I realized $(document).ready(...) works! But the real problem is that $('#demo') is undefined! (I checked the console-I'm using SDK version of node-webkit)

I don't know if it's because of node-webkit or something else I'm missing?


Solution

  • found the solution, I should define jquery like this:

    window.$ = window.jQuery = require('jquery')
    

    this is simply because of variable scopes in ECMAS

    so if I define it like this, I can use it everywhere