I have made a simple code using require js. but output of another.js file is not coming to DOM.
this is my index.html.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Require JS app</title>
<script data-main="js/main" src="js/require.js"></script>
</head>
<body>
<div id="myapp"></div>
</body>
</html>
This is main.js file
require.config({
baseUrl: 'js/lib',
paths: {
"app": "../apps"
}
});
require(['jquery','app/another'], function($,message3) {
$('#myapp').html(message3);
})
This is another.js file
require (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
and this is anotherfile.js
define(function(){
var message2="hello world";
return(message2);
})
In another.js file replace
require (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
with
define (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
and it will work
Related
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>
I created a project with the generator for Chrome extensions. Below is a representation of my folder structure.
my-wonderful-chrome-extension
app
scripts
common.js
test
index.html
spec
test.js
I want to test the common.js. My understanding of Mocha is that I should have a index.html file like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mocha Spec Runner</title>
<link rel="stylesheet" href="bower_components/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="bower_components/mocha/mocha.js"></script>
<script>
mocha.setup('bdd');
mocha.reporter('html');
</script>
<script src="bower_components/chai/chai.js"></script>
<script>
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should();
</script>
<!-- include source files here... -->
<script src="../app/scripts/common.js"></script>
<!-- include spec files here... -->
<script src="spec/test.js"></script>
<script>mocha.run()</script>
</body>
</html>
The test file (test.js) looks like this:
/* global describe, it */
describe('Find the root recipe node', function () {
it('Should not find an elem in null dom', function () {
console.log(dds_hmr.findRecipeRoot);
});
});
The common.js file looks like this:
var dds_hmr = {};
dds_hmr.findRecipeRoot = function (elem) {
if (elem && elem.hasAttribute("itemtype")
&& elem.getAttribute("itemtype") === "http://schema.org/Recipe") {
return [elem];
} else {
var result = [];
if (elem) {
for (var i = 0; i < elem.childNodes.length; i++) {
var child = dds_hmr.findRecipeRoot(elem.childNodes[i]);
result.concat(child);
}
}
return result;
}
};
This is the error I'm getting:
1) Find the root recipe node Should not find an elem in null dom:
ReferenceError: Can't find variable: dds_hmr
at http://localhost:9000/spec/test.js:4
at http://localhost:9000/bower_components/mocha/mocha.js:4263
at http://localhost:9000/bower_components/mocha/mocha.js:4635
at http://localhost:9000/bower_components/mocha/mocha.js:4694
at next (http://localhost:9000/bower_components/mocha/mocha.js:4561)
at http://localhost:9000/bower_components/mocha/mocha.js:4570
at next (http://localhost:9000/bower_components/mocha/mocha.js:4514)
at http://localhost:9000/bower_components/mocha/mocha.js:4538
at timeslice (http://localhost:9000/bower_components/mocha/mocha.js:5531)
What do I need to do to get the test to reference the code in the common.js file?
Turns out that the solution lies in the Grunt configuration (makes sense). In the connect key for the grunt server there is a test key. Under the property options there is another property base. Add 'app' to that list. This will include the app directory at test execution time. From there the trick is to change the script include in the index.html from
<!-- include source files here... -->
<script src="../app/scripts/common.js"></script>
to
<!-- include source files here... -->
<script src="scripts/common.js"></script>
Update: Added the Grunt section
// Grunt server and debug server setting
connect: {
options: {
port: 9000,
livereload: 35729,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
chrome: {
options: {
open: false,
base: [
'<%= config.app %>'
]
}
},
test: {
options: {
open: false,
base: [
'test',
'app',
'<%= config.app %>'
]
}
}
}
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'm setting up my SpecRunner.html/.js, RequireConfig.js, my paths and my shims just like I have with earlier release candidates of Jasmine + RequireJs, but now my test methods show Jasmine undefined. They've recently changed to a different method of loading Jasmine that I understand is incompatible with RequireJs.
Is my understanding correct? If so, will we ever be able to use Jasmine + RequireJs again?
The new boot.js does a bunch of the initialization and attaches it to window.onload() which has already been called by the time require.js loads Jasmine. You can manually call window.onload() to initialize the HTML Reporter and execute the environment.
SpecRunner.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<!-- specRunner.js runs all of the tests -->
<script data-main="specRunner" src="../bower_components/requirejs/require.js"></script>
</head>
<body>
</body>
</html>
specRunner.js
(function() {
'use strict';
// Configure RequireJS to shim Jasmine
require.config({
baseUrl: '..',
paths: {
'jasmine': 'tests/lib/jasmine-2.0.0/jasmine',
'jasmine-html': 'tests/lib/jasmine-2.0.0/jasmine-html',
'boot': 'tests/lib/jasmine-2.0.0/boot'
},
shim: {
'jasmine': {
exports: 'window.jasmineRequire'
},
'jasmine-html': {
deps: ['jasmine'],
exports: 'window.jasmineRequire'
},
'boot': {
deps: ['jasmine', 'jasmine-html'],
exports: 'window.jasmineRequire'
}
}
});
// Define all of your specs here. These are RequireJS modules.
var specs = [
'tests/spec/routerSpec'
];
// Load Jasmine - This will still create all of the normal Jasmine browser globals unless `boot.js` is re-written to use the
// AMD or UMD specs. `boot.js` will do a bunch of configuration and attach it's initializers to `window.onload()`. Because
// we are using RequireJS `window.onload()` has already been triggered so we have to manually call it again. This will
// initialize the HTML Reporter and execute the environment.
require(['boot'], function () {
// Load the specs
require(specs, function () {
// Initialize the HTML Reporter and execute the environment (setup by `boot.js`)
window.onload();
});
});
})();
Example spec
define(['router'], function(router) {
'use strict';
describe('router', function() {
it('should have routes defined', function() {
router.config({});
expect(router.routes).toBeTruthy();
});
});
});
Here's an alternative approach that may be simpler in some cases - use Jasmine's asynchronous support to load your AMD module before executing tests, like this:
in MySpec.js:
describe('A suite', function() {
var myModule;
// Use require.js to fetch the module
it("should load the AMD module", function(done) {
require(['myModule'], function (loadedModule) {
myModule = loadedModule;
done();
});
});
//run tests that use the myModule object
it("can access the AMD module", function() {
expect(myModule.speak()).toBe("hello");
});
});
For this to work, you'll need to include require.js in your SpecRunner.html and possibly configure require (as you normally would, e.g. by setting the baseUrl), like this:
in SpecRunner.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<script src="lib/require.min.js"></script>
<script> require.config({ baseUrl: "src" }); </script>
<script src="lib/jasmine-2.0.0/jasmine.js"></script>
<script src="lib/jasmine-2.0.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.0.0/boot.js"></script>
<script src="spec/MySpec.js"></script>
</head>
<body>
</body>
</html>
For this example, the AMD module implementation might look something like this:
in src/myModule.js:
define([], function () {
return {
speak: function () {
return "hello";
}
};
});
Here's a working Plunk that implements this complete example.
Enjoy!
In my simple index file i added the "requirejs" - and calling the define function, but i am not getting any response:
Html :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script data-main="js/main" src="js/lib/require.js"></script>
</body>
</html>
main.js :
require.config({
baseUrl : "js"
})
require(function () {
alert("hi");
})
I found a solution: and it describes as :
require(["helper/util"], function(util) {
//This function is called when scripts/helper/util.js is loaded.
//If util.js calls define(), then this function is not fired until
//util's dependencies have loaded, and the util argument will hold
//the module value for "helper/util".
});
at here : http://requirejs.org/docs/start.html
thanks for all.