0

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 wich 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 it's 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 adress 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

Community
  • 1
  • 1
Raphael
  • 1,709
  • 2
  • 17
  • 27

2 Answers2

2

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);
cspotcode
  • 1,832
  • 1
  • 13
  • 17
0

why not just conditionally set the externals property based on where you're calling webpack? using an environment variable or something

rossipedia
  • 56,800
  • 10
  • 90
  • 93
  • you mean something like try { var $ = require('jquery') } catch(e) { var $ } in my files? The problem is I need it on server side. – Raphael Mar 02 '16 at 15:58