jquerynode.jsreactjswebpack

React serverside, webpack


I want to render a React app on the serverside and have dependencies handling problems.

More precisely, I want to load jQuery from CDN and be able to do

require('jquery')

in my application's files. Everything works well on the client side, I have a webpack config file which looks like this:

# webpack.config.js 
externals : {
    "jquery": "jQuery",
}

and jQuery is simply loaded in an html file:

# index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

I am not able to make this work serverside. If I understand well, this has nothing to do with webpack, which is a only a bundler and its job is not to actually load the files. Once again, if I understand well, this should be done by my node server which actually renders the React component.

# server.js
var reactRender = require('react-render');
reactRender({path: '/abs/path/to/component.js', ...});

The problem is that require('jquery') does not work in this context. Here (using webpack on server side of nodejs) I found an example on how to use webpack serverside but it does not address the issue of externals components not installed in node_modules.

I also tried to use script.js (https://github.com/ded/script.js) to first load jQuery from CDN and then render the app, but it requires the document component, which is undefined serverside.

# this does not work
$script(['https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'], 'bundle');
$script.ready('bundle', function() {
    reactRender(...)
});

Any thought is much appreciated! Thanks


Solution

  • In the past I've used domino combined with jquery to manipulate HTML server-side. Domino is a JavaScript implementation of the DOM. I'm not a react expert, but this may work for you:

    npm install --save domino jquery
    

    And then:

    // Create a window object.  See also: https://github.com/fgnass/domino#usage
    const domino = require('domino');
    const window = domino.createWindow('');
    const document = window.document;
    
    // Create a jquery instance
    const $ = require('jquery')(window);