Experiencing problems when using jQuery in a nodejs context

时间:2015-09-01 22:28:49

标签: jquery node.js electron

I'm writing an app using atom/electron which is entirely built from an existing html/css/js source.

After a few hours tweaking grunt scripts i finally got something building. However, I kept getting the following error:

Uncaught ReferenceError: jQuery is not defined

After some playing around and general bashing my head against a wall I finally realised that this clever little bit of the jQuery source was to blame.

Inparticular, this line

if ( typeof module === "object" && typeof module.exports === "object" ) {
    // Assume node context
}

So I'm not going insane. jQuery is in-fact loaded but it is bootstrapped to the node context instead of the browser context, causing all successive plugins to complain that window.jQuery is not defined.

My first thought was to throw in this cheeky snippet after the jquery source

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    global.jQuery = global.$ = window.jQuery = window.$ = module.exports;
}

This looks like it has done the trick. However, I'm no expert on atom/electron/webkit. Does anyone know of a cleaner way around this and whether changing the module.exports of a file included in a <script> tag is wise?

Cheers

1 个答案:

答案 0 :(得分:1)

我也有同样的问题。我不知道我在哪里找到了这个解决方案,但这对我来说很好。

如果你想在电子中使用jQuery,你应该在每个html文件中都需要它作为模块。比jQuery工作或其他需要jQuery的框架。

<script>$ = jQuery = require("jquery")</script>

要安装jQuery模块,请使用npm

npm install --save jquery