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.
Related
I am trying to use a method from a javascript module and i dont understand why i get this error :
index.html:5
Uncaught ReferenceError: starts is not defined
at window.onload (index.html:5:11)
I have 2 js files and a html one and all are in the same folder.
connect.js
function start(){
console.log("ok");
}
main.js
import{start} from './connect.js';
export{starts};
function starts(){
start();
console.log("started script");
}
Index.html
<html>
<body>
<script type="text/javascript" >
window.onload=function(ev){
starts();
};
</script>
</body>
<script type="module" src="./connect.js"></script>
<script type="module" src="./main.js"></script>
</html>
If you are trying to use modules from the local filesystem (by directly opening index.html), this is not allowed due to CORS restrictions. See this for more details: javascript modules and CORS
If there are no other project requirements regarding the use of modules, you may use the scripts without type="module" and remove import/export statements from main.js. Otherwise, you would need a server.
You have made a spelling mistake in second line of your main.js
Use export{start} instead of export{starts}; And also change that in HTML file.
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>
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
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
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.