requiring RX.js in node.js

- 1 answer

Ad

I am getting an error when requiring rx into my file. in the browser console it says "Uncaught ReferenceError: require is not defined"

checked version and ref on github but don't see what it still doesn't work? simply want to try using a alert msg when clicking on the button.

here's my observ.js file located in /js

var Rx = require('rx');
var Observable = Rx.Observable;

var button = document.getElementById('button');

var handler = function(e) {
  alert('clicked!');
};

button.addEventListener('click', handler);

here is my html file located in /public

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
    <button id="button">Click me</button>
  <script src="../js/observ.js"></script>
</body>
</html>

here is my express js app just serving html in root folder

var express = require('express');
var app = express();


app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
  res.render('index');
});

app.listen(process.env.PORT || 3000, function() {
  console.log('Express listening on port 3000');
});
Ad

Answer

Ad

Looking at the documentation. It looks like you need to use an AMD loader like require.js to run this code on the client side.

For example:

<html>
<head>
    <title>test</title>
</head>
<body>
    <button id='button'>Test</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
    <script>
        requirejs.config({
            paths: {
                rx: 'rx'
            }
        });

        requirejs(['rx'], function(Rx) {
          var Observable = Rx.Observable;

          var button = document.getElementById('button');

          var handler = function(e) {
            alert('clicked!');
          };

          button.addEventListener('click', handler);

        });
    </script>
    </body>
</html>

To see working example, follow these steps.

  1. Copy the above code,
  2. Create a new local folder / html file
  3. Paste the above code in the HTML file
  4. Create a new file called rx.js at the root of your new folder
  5. Copy rx code from here and paste it in the rx.js file

Note: I have verified that this works. But you may want to also look at browserify if you are looking for more of an Isopmorphic approach.

Ad
source: stackoverflow.com
Ad