AngularJS and RequireJS - Uncaught Error: No module: MyApp - javascript

I am trying to create a new angular project with requireJS.
here is my index.html:
<!doctype html>
<html ng-app="MainApp">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script data-main="js/requirejs.config.js" src="common/lib/requirejs/require.js"></script>
<title>{{'TITLE' | translate}}</title>
<link rel="stylesheet" href="common/lib/bootstrap-3.1.1-dist/css/bootstrap.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body ng-controller="MainCtrl" ng-cloak class="ng-cloak">
<button type="button" class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-star"></span>{{'HELLO' | translate}}
</button>
</body>
</html>
and here is my requirejs.config.js:
require.config({
baseUrl: 'common',
paths: {
angular : 'lib/angular-1.2.19/angular',
jquery : 'lib/jquery/jquery-2.1.1',
uibootstrap : 'lib/ui-bootstrap-0.11.0/ui-bootstrap-tpls-0.11.0',
bootstrap : 'lib/bootstrap-3.1.1-dist/js/bootstrap',
app : '../js/app',
config : '../js/config'
},
shim : {
angular : {
exports: 'angular'
},
jquery : {
exports: 'jquery'
},
uibootstrap : {
exports: 'uibootstrap'
},
bootstrap : {
exports: 'bootstrap'
}
},
// To remove urlArgs on production
urlArgs: "v=" + (new Date()).getTime() * Math.random()
});
require([
'../js/MainCtrl'
]);
every 2nd hit of F5 on the browser with the index.html loaded i receive the error:
"[$injector:nomod] Module 'MainApp' 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.
Any ideas why?
P.S - removing the ng-app="MainApp" tag and bootstrapping the angular manually after the dom is loaded resolves it, but i'm affraid iv'e done something wrong and want to make sure
EDIT - here is my app.js:
define(["angular", "config"], function(angular) {
return angular.module('MainApp', ['common']);
});
Here is my config.js:
define([
"angular",
"constants/constants",
"values/values",
"filters/filters",
"services/services",
"factories/factories",
"directives/directives",
"providers/providers",
"controllers/controllers"
], function(angular) {
return angular.module('common', [
'common.factories',
'common.services',
'common.directives',
'common.providers',
'common.constants',
'common.values',
'common.controllers',
'common.filters'
]);
});

Just check if the immediately parent folder has any space character in the name, as for my case - my folder structure was like.../In Progress/AngularSample/
I had the same issue, and apparently no issue in code, I eventually changed the parentfolder name from "In Progress" to "In-Progress" and it started working correctly!

Related

angular runtime, styles and polyfiles get a 404 error on my web server

I have made a little Angular application, I have built it on my computer, but when I try to open the index.html file I have 404 errors, I tried to deploy it on a web server but it's the same :
GET http://www.valhatech.com/runtime-es2015.edb2fcf2778e7bf1d426.js net::ERR_ABORTED 404 (Not Found)
GET http://www.valhatech.com/styles.365933d9cb35ac99c497.css net::ERR_ABORTED 404 (Not Found)
GET http://www.valhatech.com/polyfills-es2015.2987770fde9daa1d8a2e.js net::ERR_ABORTED 404 (Not Found)
My index.html file is that :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>McKenzieEquation</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="assets/js/app.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
And the content of my app.module.ts is :
const routes: Routes = [
{ path: 'home', component: AppComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', redirectTo: 'home' }
];
#NgModule({
declarations: [
AppComponent,
MckenzieGraphComponent
],
imports: [
BrowserModule,FormsModule,RouterModule.forRoot(routes, { useHash: true })
],
providers: [MckenzieEquationService],
bootstrap: [AppComponent]
})
export class AppModule { }
Firefox console send me on a Reason: CORS request not HTTP error or URI of module source is not authorized in this document : « file:///polyfills-es2015.2987770fde9daa1d8a2e.js ».
I have found my error. On my web server my angular page was located to the following path :
/www/mckenzieequation
And my index file was written like that :
<head>
<meta charset="utf-8">
<title>McKenzieEquation</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="assets/js/app.js"></script>
</head>
I have to replace the base parameter with the following code :
<base href="/mckenzieequation/">
The base href must pointing to the place of the index file.

Socket.io variable not defined in Phonegap mobile application

I'm trying to develop a mobile application using Phonegap with RequireJs, Backbone, jQuery and I'm running into a problem each time I try to include the requirejs script tag:
<script data-main="js/app" src="node_modules/requirejs/require.js</script>
After I include this, I get the following error:
ReferenceError: io is not defined.
I'm not using socket.io but I think that Phonegap is using it in order to refresh the page in the browser.
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
<title>Hello World</title>
</head>
<body>
something nice
<!-- Content -->
<script type="text/javascript" src="cordova.js"></script>
<script data-main="js/app" src="node_modules/requirejs/require.js"></script>
</body>
</html>
This is my js/app.js file:
requirejs.config({
baseUrl: 'js',
shim: {
'socket.io': {
exports: 'io'
},
'underscore': {
exports: '_'
},
'backbone': {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
}
},
paths: {
jquery: 'jquery.min',
underscore: 'lodash.min',
backbone: 'backbone',
socketio: '../socket.io/socket.io'
// package: 'node_modules'
}
// map: {
//
// '*': {
// 'jquery': 'private/jquery'
// },
//
// 'private/jquery': {
// 'jquery': 'jquery'
// }
// }
});
I'm using Phonegap version 6.3.4.
Could you please tell me, what should i do in order to get rid of the error?
Thank you!
I've managed to solve it by reading these articles:
Has Phonegap integrate socket.io in version 3.5.0-0.20.10?
https://github.com/phonegap/phonegap-app-developer/issues/339
Mismatched anonymous define() module
Here's my fix:
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
// Fixes "Uncaught ReferenceError: io is not defined".
// We need to load RequireJs after socket.io has been loaded.
function injectRequireJs() {
var h = document.getElementsByTagName('body')[0];
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'node_modules/requirejs/require.js';
s.setAttribute('data-main', 'js/bootstrap');
h.appendChild(s);
}
setTimeout(function(){
injectRequireJs();
}, 1);
</script>

AngularJS + RequireJS. Unknown provider: $routeProvider?

I am trying to use Angular with RequireJS, and am having a problem with Angular routing. The error I receive is " Unknown provider: $routeProvider" so I know that the ngRoute dependency is not working. I have no idea why. Here is my code below, can someone please help me?
index.html
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<!-- <script src="js/vendor/modernizr-2.8.3.min.js"></script> -->
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<div id="main">
<div ng-view>
</div>
<script data-main="js/main" src="js/vendor/require.js">
</body>
</html>
main.js
require.config({
paths: {
'angular': 'vendor/angular',
'domReady': 'vendor/domready',
'ngRoute': 'vendor/angular-route'
},
shim: {
'angular': {
exports: 'angular'
},
'ngRoute': {
deps: ['angular']
}
},
deps: ['./bootstrap']
});
bootstrap.js
/**
* bootstraps angular onto the window.document node
*/
require([
'require',
'angular',
'ngRoute',
'./app',
'./routes'
], function (require, ng) {
'use strict';
require(['domReady!'], function (document) {
ng.bootstrap(document, ['app']);
});
});
app.js
define('app',
[
'angular',
'ngRoute'
], function(ng) {
'use strict';
console.log('app.js loaded');
var app = ng.module('app', ['ngRoute']);
console.log(app);
return app;
});
routes.js
require(['app'], function(app) {
'use strict';
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: './views/home.html',
controller: 'homeCtrl'
});
}]);
});
I fixed the problem myself. Here is my new main.js and bootstrap.js Hope it might help someone else having trouble with RequireJS + ngRoute. I still need to seperate my app.config into another file, but for now this solution is working nicely. Thank goodness.
main.js
require.config({
paths: {
'angular': 'vendor/angular',
'domReady': 'vendor/domready',
'angularRoute': 'vendor/angular-route'
},
shim: {
'angular': {
exports: 'angular'
},
'angularRoute': {
deps: ['angular'],
exports: 'angularRouter'
}
},
deps: ['./bootstrap']
});
bootstrap.js
require(['angular', 'angularRoute'], function (angular, angularRoute) {
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'js/views/home.html'
})
.otherwise('/');
});
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
});

JavaScript errors are not showing after minification

I'm using r.js to minify js files in cordova based project. Unminified code is working fine, but after minifying nothing is working, not even console.log is working(which was placed in first line of the files which was loaded from index.html file), not even single error is being thrown.
So, I wanted to check whether minified code is throwing any errors at all even though if unminified code has errors. So, I changed some code(by changing object name to appp from app, and calling app.initialize) so that i can get an error in console(in unminified version). As expected I'm getting error in console with unminified version of code, where as minified version of same code(which has error) is not throwing any error.
I should be getting errors in minified code,even though the error is understable.First off I'm not getting any errors.So I don't know why nothing is working after minification, If i get some errors then I can find what exactly the problem with minified code.I don't know why this is happening.
Is anything I'm doing wrong here?
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' https://* 'unsafe-inline' 'unsafe-eval'"/>
<title>Title</title>
</head>
<body>
<div id="mainContainer">
<!-- rootviewTpl -->
</div>
<div id="modals-demo">
<div class="row">
<div class="col s12">
<div id="modal" class="modal"></div>
</div>
</div>
</div>
<div class="loader" id="loader">
</div>
<script type="text/javascript" src="cordova.js"></script>
<script src="lib/js/lock-7.10.3.js"></script>
<script src="lib/js/winstore-jscompat.js"></script>
<script src="lib/js/jwt-decode.min.js"></script>
<script type="text/javascript" src="js/config-variables.js"></script>
<script data-main="js/index.js" src="lib/js/require-2.0.0.js"></script>
</body>
</html>
index.js
define([
"./config"
], function(){
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
require(["js/database/FTMobileDatabase"]);
}
};
app.initialize();
});
config.js:
requirejs.config({
baseUrl: "lib/js",
paths: {
js: "../../js",
templates:"../../templates",
jquery:"jquery.min",
underscore:"underscore.min",
backbone:"backbone",
handlebars:"handlebars",
marionette:"backbone.marionette.min",
d3: "d3",
"d3.chart": "d3.chart",
//materialze library
velocity:"velocity.min",
hammerjs:"hammer.min",
materialize:"materialize.min",
//date libraries
moment:"moment",
hbs: 'require-handlebars-plugin/hbs'
},
shim:{
"jquery":{
deps:[],
exports:"jquery"
},
"underscore": {
deps:[],
exports: "_"
},
"backbone": {
deps: ["jquery", "underscore"],
exports: "Backbone"
},
"marionette":{
deps:["backbone"],
exports:"Marionette"
},
"handlebars":{
deps:[],
exports:"Handlebars"
},
"d3": {
deps:[],
exports: "d3"
},
"d3.chart": {
deps: ["d3"],
exports: "d3Chart"
},
"materialize":{
deps:["jquery","velocity","hammerjs"],
exports:"materialize"
},
"moment":{
deps:[],
exports:"moment"
},
hbs: { // optional
helpers: true, // default: true
templateExtension: 'hbs', // default: 'hbs'
partialsUrl: '' // default: ''
}
},
waitSeconds: 0
});
build.json:
({
appDir: "./www",
dir:"./www",
mainConfigFile:"./www/js/config.js",
modules:[
{
name:"js/index",
include:[
"js/database/FTMobileDatabase"
],
exclude:[
"js/config"
]
}
],
preserveLicenseComments: false,
allowSourceOverwrites: true,
keepBuildDir:true
})

Requirejs not loading a jquery plugin

I'm working on improving the tests for jquery-csv (jquery plugin).
I can currently run a full suite of tests (ie mocha/chai) from the command line with no problems. I'm having issues figuring out how to use require.js to load dependencies so I can extend the test runner to work with mochaphantomjs tests.
The HTML used to load RequireJS:
<!doctype html>
<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 data-main="scripts/app" src="scripts/require.js"></script>
</body>
</html>
The RequireJS module:
require.config({
baseUrl: '/',
paths: {
'jquery' : '../../node_modules/jquery/dist/jquery',
'jquery-csv' : '../../src/jquery.csv',
'mocha' : '../../node_modules/mocha/mocha',
'chai' : '../../node_modules/chai/chai',
},
shim: {
'mocha': {
exports: 'mocha'
},
'chai': {
exports: 'chai'
},
'jquery-csv' : {
deps: ['jquery'],
exports: 'jQuery.fn.csv',
}
},
});
define(function(require) {
require('jquery');
require('jquery-csv');
// chai setup
var chai = require('chai');
var expect = chai.expect();
var should = chai.should();
// mocha setup
var mocha = require('mocha');
mocha.setup('bdd');
mocha.reporter('html');
mocha.bail(false);
require(['test.js'], function(require) {
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
}
else {
mocha.run();
}
});
});
Note: The define function is using the CommmonJS style.
The error I'm getting is:
Uncaught Error: Module name "../src/jquery.csv.js" has not been loaded yet for context: _. Use require([])
AFAIK, the shim should have fixed this issue by loading jQuery first and attaching the plugin to it.
I'm pretty new to RequireJS, is there something obvious I'm missing?
Try to add your "jquery-csv" as dependency in:
require(['test.js', 'jquery', 'jquery-csv'], function(require, $) {
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
}
else {
mocha.run();
}
});

Categories

Resources