Require.js -- how to load relative to a module directory - javascript

My structure looks like so:
index.html
main.js #holds the configs.path and configs.shim
libs
jquery.js
require.js
backbone.js
underscore.js
modules
app
main.js #want to load in ./views/app.js here
views
app.js
so in /modules/app/main.js, I want to load in the /modules/app/views/app.js but having problem
Here is /modules/app/main.js
define(['views/app'],function(App){
console.log('app main')
//var app = new App();
})
The console error message I get is Get failed with path GitProjects/GameApp/views/app.js
How do I get it to load relatively inside modules?
here is ./main.js the file that holds the configs
require.config({
paths: {
jquery: './libs/jquery-2.0.3',
underscore: './libs/underscore',
backbone: './libs/backbone'
},
shim: {
"underscore": {
exports: '_'
},
"backbone": {
deps: ["underscore", "jquery"],
exports: "Backbone"
}
}
});
and here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Stop Game App</title>
<script src="./libs/require.js" data-main='./main'></script>
</head>
<body>
<div id="app"></div>
<script>
require(['./modules/app/main'],function(){
console.log('main')
})
</script>
</body>
</html>

You just need to set the path to "./" and be relative. That's all there is to it.

Related

RequireJS can not find a JavaScript module

I have an index.html file which specifies the location of a main.js to RequireJS. I have a pure client side site and I am trying to require other RequireJS modules from the server. The code worked last week, all of sudden I started getting this error without changing the code.
Here's the HTML code. In the tag, I am specifying the path to find the main.js to RequireJS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Doc View</title>
<link rel="stylesheet" href="assets/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css" />
<link rel="stylesheet" href="assets/css/app.css" />
<script data-main="views/main.js" src="assets/lib/requirejs/require.js">
</script>
<base href="/viva_med_web_local_version/">
</head>
<body>
<div class="ng-cloak">
<div ui-view="header"></div>
<div ui-view="content"></div>
<div ui-view="footer"></div>
</div>
</body>
</html>
I have main.js in my views. My project structure look like this:
I have no idea why I am getting this error as the path to main.js is given in the index.html. I am getting this error:
Failed to load resource: the server responded with a status of 404 (Not Found)
require.js:138 Uncaught Error: Script error for: main
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:163)
at HTMLScriptElement.onScriptError (require.js:1666)
Here's the main.js file:
requirejs.config({
waitSeconds: 1200,
paths: {
underscore: 'assets/lib/underscore/underscore',
angular: 'assets/lib/angular/angular',
'angular-cookies': 'assets/lib/angular-cookies/angular-cookies.min',
'amcharts': 'assets/lib/amcharts_3.21.2/amcharts/amcharts',
'amcharts-serial': 'assets/lib/amcharts_3.21.2/amcharts/serial',
'amcharts-angular': 'assets/lib/amcharts-angular/dist/amChartsDirective',
'angular-route': 'assets/lib/angular-route/angular-route',
'angular-ui-route': 'assets/lib/angular-ui-router/release/angular-ui-router',
'ui.bootstrap': 'assets/lib/angular-bootstrap/ui-bootstrap-tpls',
'bootstrap': 'assets/lib/bootstrap/dist/js/bootstrap.min',
'jquery': 'assets/lib/jquery/dist/jquery'
// more configuration
},
shim: {
underscore: {
exports: '_'
},
'angular': {
exports: 'angular'
},
'angular-ui-route': {
deps: ['angular']
},
'amcharts-serial': {
deps: ['amcharts']
},
'amcharts-angular': {
deps: ['angular', 'amcharts', 'amcharts-serial']
},
'ui.bootstrap': {
deps: ['angular']
},
'states': {
deps: ['angular'],
exports: 'states'
},
'angular-route': {
deps: ['angular']
},
'bootstrap': {
deps: ['jquery']
},
'angular-cookies': {
deps: ['angular']
}
},
priority: [
'angular'
],
dir: "."
});
requirejs(['angular',
'angular-cookies',
'app',
'underscore',
'js/routes',
'bootstrap',
'jquery',
'amcharts',
'amcharts-serial',
'amcharts-angular',
'ui.bootstrap'
], function (angular, app) {
angular.element(document).ready(function () {
angular.bootstrap(document, ['App']);
document.getElementsByTagName('html')[0].dataset.ngApp = 'App';
});
});
Can someone help me? There is nothing wrong with main.js - My teammate has the same main.js and it is working for him. I tried copying his main.js, but it does not work either. I tried clearing the cache and also restarting WebStorm. It's still not working.

I am trying to bootstrap angularjs and Requirejs,but I always end up with dependency injection error [duplicate]

This question already has answers here:
AngularJS cannot find module with latest RequireJS
(2 answers)
Closed 6 years ago.
Actually I have been trying to develop a single page application using requirejs and angularjs. I have loaded all files that are necessary,while running the app without any other angular apps and without dependencies everything works fine,but when I call the requirejs definedjs files to load within the define() in app.js the application throws the following error,
[$injector:nomod] Module 'app' 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.
Here is my html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advances in Central Science</title>
<link rel="icon" href="assets/images/favicon.ico" type="image/x-icon">
<!-- Requirejs -->
<script data-main="client/js/main" src="client/bower_libs/requirejs/require.js"></script>
</head>
<body>
<div ng-controller="mainCtrl">
<h1>{{message}}</h1>
<button class="btn btn-success">Success</button>
</div>
</body>
</html>
My Requirejs
// requirejs
require.config({
baseUrl: '/',
paths: {
// Aliases and paths of modules
'angular': 'client/bower_libs/angular/angular',
'uiRouter': 'client/bower_libs/angular-ui-router/release/angular-ui-router.min',
'bootstrap': 'client/bower_libs/bootstrap/dist/js/bootstrap.min',
'jquery': 'client/bower_libs/jquery/dist/jquery.min',
// paths
'app': 'client/js/app',
'includesjs': 'client/js/includesjs',
'includescss': 'client/js/includescss',
'modules': 'client/js/controllers/main'
},
map: {
// Maps
'*': {
'css': 'client/bower_libs/require-css/css.min.js'
}
},
shim: {
// Modules and their dependent modules
'angular': { exports: 'angular' },
'uiRouter': { deps: ['angular'] },
'bootstrap': { deps: ['jquery'] }
},
// kick start application
deps: ['client/js/initialize']
});
Initialize.js
define(['app', 'includesjs'], function() {
return true;
})
app.js(I cant get what I am doing wrong here)
=========working
define(['angular'], function(angular) {
var app = angular.module('app', []);
return app;
=========not Working
define(['angular','uiRouter'], function(angular) {
var app = angular.module('app', ['ui.router']);
return app;
});
includes.js
define([
'modules/mainCtrl'
], function() {
return true;
});
mainController.js
define(['app'], function(app) {
app.controller('mainCtrl', function($scope) {
$scope.message = "Hello,the page works like a charm";
})
});
I think you only need to define the uiRouter while defining the angular.
Try something like this.
define(['angular'], function(angular) {
var app = angular.module('app', ['ui.router']);
return app;
Its because you only need to define the dependencies on module level. Not on angular framework level. Hope that solves your issue

File Hashing using AngularJS

I am currently working on a Angualar JS project based on angularAMD.
Link: http://marcoslin.github.io/angularAMD/#/home
Here we include only the necessary dependent files in needed by the controllers and not all the files.
eg.
define(['angularAMD', 'common/services/service1', 'module1/services/service2',], function (angularAMD) {
'use strict';
angularAMD.controller('abcController', function ($scope, service1, service2) {
// controller code goes here
}
I have tried Grunt Hashing but
Grunt provides hashing but the location of the hashed files changes.
This does not change the path of the files inside individual controller as a result the application fails to run. i.e service1, service2
Question
I was wondering if there was a way to hash the files when we include a new files?
Is there any other way to solve this problem?
Thanks in Advance
how do u set up your modules. Your main.js may look like this
'use strict';
require.config({
waitSeconds: 0,
urlArgs: "bust=v1.0.0",
paths: {
bootstrap: 'Scripts/bootstrap.min',
jquery: 'Scripts/jquery-1.10.2.min',
angular: 'Scripts/angular.min',
angularRoute: 'Scripts/angular-route.min',
angularAMD: 'Scripts/angularAMD.min',
app: 'ngApp/app',
appConfig: 'ngApp/app.config',
/*register Services - Start*/
service1: 'ngServices/Common/service1',
service2: 'ngServices/module/service2',
/*register Services - End*/
/*register Filters - Start*/
/*register Filters - End*/
/*register Controllers - Start*/
/*register Controllers - End*/
},
// specifying library dependencies
shim: {
'bootstrap':{ deps:['jquery']},
'angular': { deps: ['jquery'], exports: 'angular' },
'angularRoute': { deps: ['angular'] },
'angularAMD': { deps: ['angular'] }
},
// define application bootstrap
deps: ['app']
});
and in your index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body data-ng-controller="appController as appCtrl" ng-cloak>
<div >
<ng-view></ng-view>
</div>
</div>
<script data-main="main" src="Scripts/require.js"></script>
</body>
</html>
and in your controllers
'use strict';
define(['angularAMD', 'service1', 'service2'],
function (angularAMD) {
angularAMD.controller('abcController', ['service1', 'service2',
function (service1, service1) {
var self = this,
// your code
}]);
});

Using require.js and mocha.js for a browser (front-end) Javascript unit testing [duplicate]

Can I load mocha module asynchronously in browser? I can do it for sure with chai. Is there any workaround to make mocha work in amd-like style ?
require.config({
baseUrl: "/scripts",
paths: {
"mocha": "framework/mocha",
"chai": "framework/chai",
"first": "custom/first"
}
});
require(['first', 'mocha', 'chai'], function (first, mocha, chai) {
first.echo();
console.log('something');
console.log('something');
mocha.ui('tdd');
var assert = chai.assert;
suite('"Home" Page Tests', function () {
test('page should contain link to contact page', function () {
assert($('a[href="/contact"]').length);
});
});
mocha.run();
console.log('whatever');
});
in the code sample above first and chai work fine, while mocha is undefined.
Mocha is not AMD-aware so if you are going to load Mocha using RequireJS, you need a shim for it. Here is an index.html file that contains a minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
<link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" />
<script type="text/javascript" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<div id="mocha"></div>
<script>
require.config({
paths: {
mocha: 'node_modules/mocha/mocha',
},
shim: {
mocha: {
exports: "mocha",
}
},
});
require(["mocha"], function (mocha) {
mocha.setup("bdd");
it("foo", function () {});
mocha.run();
});
</script>
</body>
</html>
You need to have run npm install requirejs mocha in the same directory where index.html is located.
In cases where I want to be able to use the Mocha constructor I use this shim instead:
shim: {
mocha: {
exports: "mocha",
init: function () { return {mocha: mocha, Mocha: Mocha }; }
}
},

PhantomJS not playing nice with RequireJS+Jasmine

I have some tests running with RequireJS and Jasmine. I have a Jasmine test harness file that looks like this:
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="./Scripts/jasmine/jasmine.css" />
<script type="text/javascript" src="./Scripts/jasmine/jasmine.js"></script>
<script type="text/javascript" src="./Scripts/jasmine/jasmine-html.js"></script>
<script type="text/javascript" src="./Scripts/jasmine/boot.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
<script type="text/javascript">
require(["fakeTest"], function () {
window.onload();
});
</script>
</head>
<body>
</body>
</html>
My fakeTest file is very simple:
define(["require", "exports"], function (require, exports) {
describe("fake test", function () {
it("test nothing", function () {
expect(1).toEqual(1);
});
});
});
If I run this in FireFox/Chrome then everything works fine; I see one test and that it passed. If I run this with PhantomJS though, I start getting problems. Running it with the remote debugger flag I get the error:
Error: Cannot find module 'fakeTest'
phantomjs://bootstrap.js:299 in require
phantomjs://bootstrap.js:263 in require
If I try changing my harness file so that it says requirejs[("fakeTest"...... instead of just require, I get this error:
Error: Script error for "fakeTest"
http://requirejs.org/docs/errors.html#scripterror
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:140
in defaultOnError
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:544
in onError
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1732
in onScriptError :0 in appendChild
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1952
in load
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1679
in load
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:829
in load
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:819
in fetch
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:851
in check
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1177
in enable
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1550
in enable
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1162
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:131
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:56
in each
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1114
in enable
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:783
in init
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1453
If I put in a completely invalid module name, I get the same errors in both cases.
I'm totally lost as to why this is happening. I've played around with changing the path for fakeTest in the harness file but nothing changes. I've simplified the harness file as much as I could, but since I'm still seeing this i'm not sure what else to try. Anyone have any ideas?
edit
I've removed everything to do with Jasmine and just have fakeTest do an alert. Now I get errors saying
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script>
<script type="text/javascript">
require(["fakeTest"], function () {});
</script>
</head>
<body>
</body>
</html>
and
define(["require", "exports"], function (require, exports) {
alert('foo');
});
"ReferenceError: Can't find variable: requirejs"
Instead of write html use karma with requirejs plugin.
karma.conf.js
module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'Scripts/**/*.js', included: false},
{pattern: 'test/*.js', included: false},
'test/test-main.js'
],
// list of files to exclude
exclude: [],
browsers: ['PhantomJS']
});
};
test/test-main.js
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
// example of using a couple path translations (paths), to allow us to refer to different library dependencies, without using relative paths
paths: {
// Put Your requirejs config here
},
// example of using a shim, to load non AMD libraries (such as underscore)
shim: {
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
This is example files. Fix it and run
karma run
Instead of
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
use
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"
data-main="Tests/main"></script>
Move test files to Tests directory.
In Tests/main.js use Your requirejs config and run main tests file.
var deps = ['Tests/fakeTest'];
require.config({
baseUrl: '..',
paths: {
'jasmine': ['Scripts/jasmine//jasmine'],
'jasmine-html': ['Scripts/jasmine/jasmine-html'],
'jasmine-boot': ['Scripts/jasmine/boot']
},
// shim: makes external libraries compatible with requirejs (AMD)
shim: {
'jasmine-html': {
deps : ['jasmine']
},
'jasmine-boot': {
deps : ['jasmine', 'jasmine-html']
}
}
});
require(['jasmine-boot'], function () {
require(deps, function(){
//trigger Jasmine
window.onload();
})
});
In index.html run only Tests/main.js file:
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="./Scripts/jasmine/jasmine.css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js" data-main="Tests/main"></script>
</head>
<body>
</body>
</html>

Categories