require.js with angular and jquery cause script error - requirejs

Good day. I am beginner at require.js.
I have next scripts and css's in my html (style.css and script.js located at the same folder, where html is):
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel='stylesheet' href='style.css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.27/angular.js"></script>
<script src="https://cdn.bootcss.com/angular-ui-router/0.2.18/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.27/angular-animate.js"></script>
<script src="script.js"></script>
I am adding require.js as a first script:
<script data-main="main" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.1/require.js"></script>
and adding main.js, writing there:
requirejs.config({
baseUrl:"",
paths: {
"jquery":"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js",
"bootstrap":"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
(etc etc)
}
});
define(["jquery"], function() {
});
define(["bootstrap"], function() {
});
etc
I got
Error: Script error for "jquery", needed by: main
http://requirejs.org/docs/errors.html#scripterror
what I have to fix?

From RequireJS Documentation:
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//**never includes a ".js" extension since
//the paths config could be for a directory**.
paths: {
app: '../app'
}
});
Paths are not supposed to end with ".js". Your code should work fine by removing the ".js" from your paths.

Related

Requiring modules gives module not loaded error

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>

node js chai mocha "ReferenceError: Can't find the variable require"

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...

Require JS not working properly

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

Does Jasmine 2.0 really not work with require.js?

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!

Mocha tests with Yeoman and PhantomJS

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']
},

Resources