requirejs http://requirejs.org/docs/errors.html#scripterror - javascript

I am trying to get my hands on require.js which is new for me but I cannot have it work. After having followed some simple tutorials for beginners, I proceeded to create my first (fairly simple project).
I am using visual studio 2013 (as I am a .net guy)
This is a quick way on my file structure
./content
/*a bunch of css files*
./Scripts
/jquery-1.9.1.js
/sandbox.js (!! my library !!)
.index.html (on the root)
.app.js (on the root)
Here is my module: sandbox.js
//sandbox.js
require.config({
paths:{
"jquery":"/Scripts/jquery-1.9.1"
}
});
define(["jquery"], function($){
var show_name = function(n){
alert(n);
};
return{
showName : display_name
}
});
And now in the app.js I make use of the module sandbox.js. Here is how
// app.js
require(["/Scripts/sandbox"], function(sandbox){
sandbox.showName('John');
});
Finally in the index.html, I load my require.js file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="/Scripts/require.js" data-main="/Scripts/sandbox"></script>
<script src="app.js"></script>
</body>
</html>
But when I run this code I get the error
0x800a139e - JavaScript runtime error: Script error for: /Scripts/sandbox
http://requirejs.org/docs/errors.html#scripterror
This error occurs in the app.js
require(['/Scripts/sandbox'], function (sandbox) {
sandbox.showName("John");
});
Obviously there is something wrong in my way of caling and using the module sandbox.js. But I cannot figure out what the error.
Any help would be greatly appreciated.

First of all, you should change all /Scripts/* to Scripts/*.
Second thing is, you have set your data-main to Scripts/sandbox, that is, your baseUrl is set to Scripts/. So your app.js should look like:
require(["sandbox"], function(sandbox){
sandbox.showName('John');
});
And your sandbox.js should be:
require.config({
paths:{
"jquery":"jquery-1.9.1"
}
});
define(["jquery"], function($){
var show_name = function(n){
alert(n);
};
return{
showName : display_name
}
});

I have finally managed to make it work.
In my app.js, it should be "['Scripts/sandbox.js']" and not "['Scripts/sandbox']".
Hope this can help any one else with the same issue

Related

function is not defined, when it is

today i was working on a project, and i got this error.
Uncaught ReferenceError: launch is not defined
at HTMLInputElement.onclick (home.html:77)
i don't understand what i did wrong here..
Here is the index.js file:
function launch() {
console.log('test');
}
module.exports.launch = launch;
and home.html:
<script>
let func = require('./index');
let launch = func.launch();
document.getElementById('lanBTN').addEventListener('click', () => {
launch();
});
<input type="button" value="Launch!" id="lanBTN" onclick="launch()">
</script>
Any ideas why this is happening..?
Require is a commonjs module specification, it doesn't work on the browser unless you use some bundler like webpack or browserify to resolve the dependencies between all of you modules and bundles one single js file to include in your html
As #mehdi-belbal mentioned you can not use CommonJS in HTML files expect if when using module bundlers like Webpack.
Besides of that module.exports is useless here, try to link your javascript module in the head of the document. and the declared function after. that will attach to the window object and you can use them both by using window.func() and ‍func()
<head>
<script src="./index.js"></script>
</head>
<body>
...
<script>
func();
</script>
</body>

Working with multiple modules in different files in Angular js

Hello and excuse my english.
My problem is this: I'm a beginner to Angular js (currently learning with version 1.4) and I want to separate my application in two modules like this:
app.js
(function(){
var app = angular.module('store', ['store-products', 'ngAnimate', 'ui.bootstrap']);
app.controller('StoreController', function(){
...
});
app.controller('ReviewController', function(){
...
};
this.rateOnClick = function(){
...
};
this.addReview = function(product){
...
};
});
.
.
.
})();
products.js
(function(){
var app = angular.module('store-products', []);
app.directive('productTitle', function(){
...
});
app.directive('productPanels', function(){
...
});
})();
index.html
<html>
<head>
<title>My Angular App!</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-animate.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.4.js"></script>
<link href="styles.css" rel="stylesheet">
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="app.js"></script>
<script src"products.js"></script>
...
</html>
All of my files are in the same folder. app.js is the primary module, so as far I understand the includes are fine, but I still get the error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module store due to:
Error: [$injector:modulerr] Failed to instantiate module store-products due to:
Error: [$injector:nomod] Module 'store-products' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Can't someon figure out why this is happening ?
LOL, just figured out, the problem was the line:
<script src"products.js"></script>
Fixed like this:
<script src="products.js"></script>
You need to include your products script before your app script.
Do not include store-products in your app.js code because in this [ ] we add directives and there is no directive name 'store-products'

RequireJS paths not work

I'm new to RequireJS and trying to use it. I followed an example in RequireJS docs but there is some problem. I can load the jquery but not app/shell.
Root
|__index.html
|__javascripts
|__main.js
|__libs
| |__jquery.js
| |__require.js
|__app
|__shell.js
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script data-main="javascripts/main.js" src="javascripts/libs/require.js"></script>
</head>
<body>
</body>
</html>
main.js
requirejs.config({
baseUrl:'javascripts/libs',
paths:{
app:'../app'
}
});
require(['jquery','app/shell'],function($,shell){
if($ && shell){
console.info('Scripts loaded');
}
});
shell.js
define(function(){
"use strict";
return{
initModule:function(){
console.info('Module init');
}
}
});
Web Console Errors
"NetworkError: 404 Not Found - http://localhost:3000/javascripts/app../default.htmshell.js"
Error: Script error for: app/shell http://requirejs.org/docs/errors.html#scripterror
Node.js Express Console Error
GET /javascripts/app../default.htmshell.js 404
Because you have multiple folder levels, you have to set your baseUrl as the root of your application. If you want to use require(['jquery']) instead of require(['libs/jquery']), you have to specify the "alias" of it in your configuration.
requirejs.config({
baseUrl:'javascripts',
paths:{
jquery: 'libs/jquery'
}
});
Try adding your main.js file explicitly after your requirejs script tag:
<script src="javascripts/libs/require.js"></script>
<script src="javascripts/main.js"></script>
This will load your configuration file synchronously after loading requirejs thus making sure the paths are set before a module is called.
Hope it helps.

Inlcuding AMD javascript as non-AMD results in library is undefined in all sorts of DOM waiting mechanisms

Trying to create an AMD Javascript library to be included in non-AMD projects. Here's my setup:
app.coffee
define ->
class App
constructor: -> console.log 'instantiating App'
init: -> console.log 'Init called'
index.html
<body>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="dev-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log('doc', window.app);
});
$(function(){
console.log('func', window.app);
});
window.onload = function()
{
console.log('onload', window.app);
}
</script></body>
main.js
require(['cs!app'], function(app){
return window.app = new app;
});
I am building this project with r.js optimizer to get dev-latest.js as the output. Here's my build file (PS: Build is successful):
({
baseUrl: './vendor',
paths: {
app: '../app',
'require-lib': 'require'
},
name: '../main',
out: 'dev-latest.js',
include: 'require-lib',
preserveLicenseComments: false
})
When running the code in the browser here's the output:
doc undefined
func undefined
onload undefined
instantiating App dev-latest.js:1
app.init(); // running this manually in the browser console
Init called
How should I go about this and get app to load before being used ?
Using AMD you cant rely on a module being created outside of a module. The only reliable way is to load the result of a module into another module. So in your case need to create a new module which then can lsiten to $.read:
define( [App], (App)->
$(document).ready(function(){
console.log('doc', App);
});
)
Solved it by using browserify (just found about it) which uses the CommonJS form of dependency loading and saves all that clutter. Also a great template for starting projects is amitayd's grunt-browserify-jasmine setup

Check Backbone/requireJs project with Jasmine

I have a project loaded using RequireJS and I would like to test the models.
I have the following test :
require(['../../js/models/lead_sharing'], function(Lead_sharing_Model) {
describe('when instantiated', function () {
it('should exhibit attributes', function() {
var test = new Lead_sharing_Model({
attribute : 3
});
expect(test.get('attribute')).toEqual(3);
});
});
});
But I have a error " failed with error: SyntaxError: Unexpected token"...
In reality , I don't know if it's possible to test a backbone/requireJs project with Jasmine. Indeed, how can I include my views/Models... without require config (like definition of the paths...)
Thanks you
Ps : just a small edit to specify that I would like test with a a js cmd. no in a browser. :)
It is certainly possible to test a backbone/requirejs project with jasmine. Pull the same require config used by the app into the html page that drives the unit tests. For example:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="vendor/jasmine.css">
</head>
<body>
<script src="vendor/jasmine.js"></script>
<script src="vendor/jasmine-html.js"></script>
<script src="../assets/js/libs/jquery.js"></script>
<script src="../assets/js/libs/underscore.js"></script>
<script src="../assets/js/libs/backbone.js"></script>
<!-- This points to the require config that is also used by the main app. -->
<script data-main="../app/config" src="../assets/js/libs/require.js"></script>
<script>
require({ paths: { spec: "../test/spec" } }, [
// Pull in all your modules containing unit tests here.
"spec/lead-sharing-specs"
], function() {
jasmine.getEnv().addReporter(new jasmine.TrivialReporter());
jasmine.getEnv().execute();
});
</script>
</body>
</html>
Since you want to run this outside of the browser, check out PhantomJS, grunt, and grunt-jasmine-task.

Categories