I am trying to write a simple Hello world app in react.js using component based approach. So I am using requie.js. I have 4 files in the same folder namely index.html, index.js,world.js and require.js. I am having a script tag in index.html which will load index.js. But I am loading the world.js via require.js using module.exports, which would result in error. Here is my code
index.html
<head>
<script src="https://fb.me/react-0.13.3.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script data-main="index.js" src="require.js"></script>
</script>
</head>
<body>
<script type="text/jsx" src="index.js"></script>
</body>
index.js
var world = require('./world');
var Hello = React.createClass({
render:function(){
return (<div>
<div>Hello,</div>
<world/>
</div>)
}
})
var element = React.createElement(Hello);
React.render(element,document.body);
world.js
module.exports = React.createClass({
render: function(){
return (<div>World!</div)
}
})
I am intending to show Hello, World. But I'm getting the following errors
Uncaught SyntaxError: Unexpected token <
fbcdn-dragon-a.akamaihd.net/hphotos-ak-xtf1/t39.3284-6/11057100_835863049837306_1087123501_n.js:314 You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx
require.js:8 Uncaught Error: Module name "world" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
:8000/index.js:5 Uncaught SyntaxError: Unexpected token <
First of all, the component "world" should start with an upper case. I went ahead and put the code in a single file so that you can see it a little more clear:
<!DOCTYPE html>
<html>
<head>
<title>Hello React!</title>
<script src="https://fb.me/react-0.13.3.js"></script>
<!-- In-browser JSX transformer, remove when pre-compiling JSX. -->
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/jsx">
var World = React.createClass({
render: function(){
return (
<div>World!</div>
);
}
});
var Hello = React.createClass({
render:function(){
return (
<div>
<div>Hello,
<World />
</div>
</div>
);
}
});
React.render(<Hello />,document.getElementById('example'));
</script>
</body>
</html>
What I would recommend is that you setup a proper environment for development with node and npm installed. I have a project in github that is a skeleton that you can use to get up and running without having to worry about how it works for now: reactjs skeleton.
I hope this helps!
There are at least three issues here. First, you are not using the correct require syntax for asynchronous loading. Your index.js should be:
define(['world'], function(world) {
var Hello = React.createClass({
render:function(){
return (<div>
<div>Hello,</div>
<world/>
</div>)
}
})
var element = React.createElement(Hello);
React.render(element,document.body);
});
Second, since index.js and world.js are jsx files, requirejs needs a plugin that will tell it that. Something like:
https://github.com/philix/jsx-requirejs-plugin
Finally, since you are loading index.js via requirejs, you don't need:
<script type="text/jsx" src="index.js"></script>
Related
I am learning about how to create/import/export modules in Node.js,
i have gone through these and was trying to learn by creating a sample application.
I issued the command from the root folder (Poc1) "npm install requirejs", and included the file require.js in the Start.html.
When i open Start.html in browser i get -
"Uncaught ReferenceError: require is not defined", "Uncaught ReferenceError: module is not defined".
I am not sure what mistake i am making or what other files i need to include to get it working ?
For sample application below is folder structure
Poc1 folder has these files and folders (greetings.js, main.js, Start.html, node_modules)
Poc1\node_modules has (requirejs\require.js)
grreetings.js is defined as below
module.exports.sayHelloInEnglish = function(){
return "Hello";
}
module.exports.sayHelloInSpanish = function(){
return "Hola";
}
main.js is defined as below
var greetings = require("./greetings.js");
function someFunc(){
var g1 = greetings.sayHelloInEnglish();
var g2 = greetings.sayHelloInSpanish();
alert(g1);
alert(g2);
}
Start.html is defined as below
<html>
<head>
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript" src="greetings.js"></script>
<script type="text/javascript" src="node_modules\requirejs\require.js"></script>
</head>
<body>
<span>Below is button</span>
<input type="button" onclick="someFunc()" value="clickMe"/>
</body>
</html>
Ok, I think those exports aren't correct:
exports.sayHelloInEnglish = function(){
return "Hello";
}
exports.sayHelloInSpanish = function(){
return "Hola";
}
I am using grunt, mocha, and chai to run a basic unit test. My unit test looks like the following
describe('SPSearchConnection', function () {
describe('#performSearch()', function () {
it('should return zero or more results', function () {
var spSearchConnect = require('../index');
alert(spSearchConnect);
chai.assert.equal(-1, [1, 2, 3].indexOf(5));
});
});
});
Now when I run the test using grunt "grunt" I get the following error:
ReferenceError: Can't find variable: require
My gruntfile.js looks like this :
// Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Mocha
mocha: {
all: {
src: ['tests/testrunner.html'],
},
options: {
run: true
}
}
});
// Load grunt mocha task
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('default', ['mocha']);
};
My testrunner.html file looks like this :
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script>
mocha.setup('bdd')
mocha.reporter('html');
</script>
<!-- Tests -->
<script src="tests.js"></script>
<!-- Tests -->
<script></script>
<script>
// Only tests run in real browser, injected script run if options.run == true
if (navigator.userAgent.indexOf('PhantomJS') < 0) {
mocha.run();
}
</script>
</body>
</html>
Can someone tell me how to fix this please?
Your unit test has the line require('../index'), but the problem is that your test is going to run in a browser environment, which does not have a native require function (hence the ReferenceError). If you need to include a separate file you could us the "requirejs" library (which is intended for browsers). Or you could use a <script> tag in your HTML file? Or maybe just a simple Ajax call...
I have a html that looks like this:
<head>
<script src="../js/vendor/jquery-2.1.0.js"></script>
<script src="../js/vendor/react.js"></script>
<script src="../js/jsx/todo.js"></script>
</head>
<body>
<div id="ola"></div>
<script src="../js/popup.js"></script>
</body>
My todo.js is the compiled version TODO app from http://facebook.github.io/react/ minus the last line.
My last popup.js is:
$(function() {
React.renderComponent(TodoApp, document.getElementById('ola'));
})
But the page shows nothing! The console shows an error:
Uncaught TypeError: Object function (props, children) {
var instance = new Constructor();
instance.construct.apply(instance, arguments);
return instance;
} has no method 'mountComponentIntoNode' react.js:10052
I really don't know why is that, I've just tried to recreate from the example in the website. If it matters, it is in a chrome extension.
Ahhh got one line wrong on render!
popup.js should be:
React.renderComponent(TodoApp(), document.getElementById('ola'));
I am trying to update the bust variable in require.js so the browser is forced to re-fetch instead of loading resources from cache. I found here that several people have asked similar question. I am trying to try with a simple piece of code.
<html>
<head>
<title>jQuery+RequireJS Sample Page</title>
<!-- This is a special version of jQuery with RequireJS built-in -->
<script>
var require = {
urlArgs : "bust="+getRandom()
};
</script>
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<script>
function getRandom() {
var buildNumber;
$.get("/resource/buildNumber", function(data) {
buildNumber = data;
});
return buildNumber;
}
</script>
</head>
<body>
<h1 id="heading">jQuery+RequireJS Sample Page</h1>
<p>Look at source or inspect the DOM to see how it works.</p>
</body>
I am trying to get the value of my build number from a properties file on the server. But I get the following error:
Uncaught ReferenceError: getRandom is not defined
So I tried this:
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<script>
var require = {
urlArgs : "bust="+getRandom()
};
function getRandom() {
var buildNumber;
$.get("/resource/buildNumber", function(data) {
buildNumber = data;
});
return buildNumber;
}
</script>
But I get this error:
Uncaught TypeError: Property 'require' of object [object Object] is not a function
It looks like the bust variable has to be set even before require-jquery.js is declared but how do I access server side APIs without access to jquery libraries? I want to update the bust variable for every build.
Any pointers in the right directions would be really appreciated.
Thanks.
I'm using Yeoman to scaffold my project. It comes with several handy things, including a PhantomJS-based test runner.
My problem is that while my tests run correctly in the browser, they time out while trying to run them with PhantomJS in the CLI.
Here's how my test index.html looks like:
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Mocha Spec Runner</title>
<link rel="stylesheet" href="lib/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="lib/mocha/mocha.js"></script>
<!-- assertion framework -->
<script src="lib/chai.js"></script>
<!-- include source files here... -->
<script data-main="scripts/main" src="scripts/vendor/require.js"></script>
<script>
mocha.setup({ui: 'bdd', ignoreLeaks: true});
expect = chai.expect;
should = chai.should();
require(['../spec/map.spec'], function () {
setTimeout(function () {
require(['../runner/mocha']);
}, 100);
});
</script>
</body>
</html>
Here's map.spec.js:
require(['map'], function (Map) {
describe('Choropleth Map Generator', function() {
describe('Configure the map', function () {
it("should enforce mandatory parameters in the configuration", function () {
var config = {title: 'test configuration'};
var map = new Map(config);
(function () {
map.getConfig();
}).should.throw(Error);
});
});
});
});
Now, when I do yeoman test, I get this:
Running "server:phantom" (server) task
Starting static web server on port 3501
[...]
Running "mocha:all" (mocha) task
Testing index.html
<WARN> PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue. </WARN>
Aborted due to warnings.
As I said, yeoman server:test shows my assertions correctly in the browser.
I'm using Yeoman 0.9.6 and PhantomJS 1.7.0. Any help is appreciated.
I solved that same warning by double-checking the path to mocha in test/index.html
<link rel="stylesheet" href="lib/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="lib/mocha/mocha.js"></script>
What is your mocha config In Gruntfile. Do you have something like:
mocha: {
all: ['http://localhost:3501/index.html']
},