Can I use jQuery with Node.js?

前端 未结 20 1596
清歌不尽
清歌不尽 2020-11-22 05:42

Is it possible to use jQuery selectors/DOM manipulation on the server-side using Node.js?

相关标签:
20条回答
  • 2020-11-22 06:23

    Update (27-Jun-18): It looks like there was a major update to jsdom that causes the original answer to no longer work. I found this answer that explains how to use jsdom now. I've copied the relevant code below.

    var jsdom = require("jsdom");
    const { JSDOM } = jsdom;
    const { window } = new JSDOM();
    const { document } = (new JSDOM('')).window;
    global.document = document;
    
    var $ = jQuery = require('jquery')(window);
    

    Note: The original answer fails to mention that it you will need to install jsdom as well using npm install jsdom

    Update (late 2013): The official jQuery team finally took over the management of the jquery package on npm:

    npm install jquery
    

    Then:

    require("jsdom").env("", function (err, window) {
        if (err) {
            console.error(err);
            return;
        }
        var $ = require("jquery")(window);
    });
    

    0 讨论(0)
  • 2020-11-22 06:24

    Yes, jQuery can be used with Node.js.

    Steps to include jQuery in node project:-

    npm i jquery --save Include jquery in codes

    import jQuery from 'jquery';
    
    const $ = jQuery;
    
    

    I do use jquery in node.js projects all the time specifically in the chrome extension's project.

    e.g. https://github.com/fxnoob/gesture-control-chrome-extension/blob/master/src/default_plugins/tab.js

    0 讨论(0)
提交回复
热议问题