SystemJS Builder - window not defined - javascript

I am trying to build my project as a Self-Executing Bundle (SFX) with Gulp and SystemJS-Builder. When I run my gulp task, I keep getting the error, "window is not defined." I researched the issue and could not find a solution.
Here is my gulp build file
var gulp = require('gulp');
var path = require('path');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var Builder = require('systemjs-builder');
gulp.task('bundle:js', function () {
var builder = new Builder('MyApplication/application/source', 'MyApplication/application/source/config.js');
return builder.buildStatic('MyApplication/application/source/app.js', 'MyApplication/application/js/Site.min.js', {
format: "amd"
});
});
Here is my SystemJS configuration:
(function () {
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
var kendoVersion = "2016.3.914";
var map = {
text: "../Scripts/text.js",
app: "app.js",
main: "main.js",
aes: "../../../Scripts/aes.js",
jquery: "../../../Scripts/kendo/" + kendoVersion + "/jquery.min.js",
kendo: "vendor/kendo/kendo.js",
DataTables: "../../../Scripts/DataTables/datatables.js",
k: "../../../Scripts/kendo/" + kendoVersion + "/",
bootstrap: "../../../Scripts/bootstrap.js",
lodash: "../../../Scripts/lodash.js",
moment: "../../../Scripts/moment.js",
ajaxSetup: "security/ajaxSetup.js",
q: "../../../Scripts/q.js",
toastr: "../../../Scripts/toastr.js",
wizards: "viewmodels/shared",
'kendo.core.min': "../../../Scripts/kendo/" + kendoVersion + "/kendo.core.min.js"
};
var paths = {
'kendo.*': "../../../Scripts/kendo/" + kendoVersion + "/kendo.*.js",
jquery: "../../../Scripts/kendo/" + kendoVersion + "/jquery.min.js",
bootstrap: "../../../Scripts/bootstrap.js"
};
var meta = {
app: { deps: ["kendo", "jquery"] },
main: { deps: ["jquery"] },
jquery: { exports: ["jQuery", "$"], format: "global" },
kendo: { deps: ["jquery"] },
bootstrap: { deps: ["jquery"] },
'kendo.core.min': { deps: ["jquery"] },
DataTables: { deps: ["jquery"], exports: "$.fn.DataTable" },
toastr: { deps: ["jquery"] }
};
var packages = {
pages: {
main: 'views/*.html',
format: 'amd',
defaultExtension: 'html'
}
};
var config = {
baseURL: "application/source",
defaultJSExtensions: true,
packages: packages,
map: map,
paths: paths,
meta: meta
};
System.config(config);
System.import("main");
})(this);
I load SystemJS in my index page. Here is my Index.cshtml page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Application</title>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
#Styles.Render("~/application/css/site.min.css")
<script src="#Url.Content("~/Scripts/modernizr-2.8.3.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/localStoragePolyFill.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/system.js")" type="text/javascript"></script>
</head>
<body>
#Html.AntiForgeryToken()
<div id="applicationHost" class="page-wrap">
<!-- The application is rendered here -->
</div>
<script src="#Url.Content("~/application/source/config.js")" type="text/javascript"></script>
</body>
</html>
I believe the issue is this line of code in the config
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
Where does the above line of code go if not in the config?

I have fixed the issue by splitting out the configuration and startup. I previously had the configuration and startup in the same file. My configuration file has configuration only, I have a separate startup file that actually starts the application.
Index.cshtml
#using System.Web.Optimization;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Application</title>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
#Styles.Render("~/application/css/site.min.css")
<script src="#Url.Content("~/Scripts/modernizr-2.8.3.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/localStoragePolyFill.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/system.js")" type="text/javascript"></script>
</head>
<body>
#Html.AntiForgeryToken()
<div id="applicationHost" class="page-wrap">
<!-- The application is rendered here -->
</div>
<script src="#Url.Content("~/application/source/startup.js")" type="text/javascript"></script>
</body>
</html>
Startup.js
// make sure we can load AMD files
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
// fire startup
window.require(["application/source/config.js"], function () {
// start app once config is done loading
System.import("main");
});
config.js
System.config({
baseURL: "application/source",
defaultJSExtensions: true,
packages:{
pages: {
main: 'views/*.html',
format: 'amd',
defaultExtension: 'html'
}
},
map: {
text: "../Scripts/text.js",
app: "app.js",
main: "main.js",
aes: "../../../Scripts/aes.js",
jquery: "../../../Scripts/kendo/2016.3.914/jquery.min.js",
kendo: "vendor/kendo/kendo.js",
DataTables: "../../../Scripts/DataTables/datatables.js",
k: "../../../Scripts/kendo/2016.3.914/",
bootstrap: "../../../Scripts/bootstrap.js",
lodash: "../../../Scripts/lodash.js",
moment: "../../../Scripts/moment.js",
ajaxSetup: "security/ajaxSetup.js",
q: "../../../Scripts/q.js",
toastr: "../../../Scripts/toastr.js",
wizards: "viewmodels/shared",
'kendo.core.min': "../../../Scripts/kendo/2016.3.914/kendo.core.min.js"
},
paths: {
'kendo.*': "../../../Scripts/kendo/2016.3.914/kendo.*.js",
jquery: "../../../Scripts/kendo/2016.3.914/jquery.min.js",
bootstrap: "../../../Scripts/bootstrap.js"
},
meta: {
app: { deps: ["kendo", "jquery"] },
main: { deps: ["jquery"] },
jquery: { exports: ["jQuery", "$"], format: "global" },
kendo: { deps: ["jquery"] },
bootstrap: { deps: ["jquery"] },
'kendo.core.min': { deps: ["jquery"] },
DataTables: { deps: ["jquery"], exports: "$.fn.DataTable" },
toastr: { deps: ["jquery"] }
}
});
I am not sure that this is the correct solution, but it did solve the "window not defined" issue.

Related

Angular app causes Uncaught SyntaxError: Unexpected identifier on import-from in JavaScript

I've included video.js 5.16.0 and videojs-record 1.6.0 in my Bower.json, the resulting JavaScript code gets injected in the following index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>SelectPOP</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<meta charset="UTF-8">
<meta name="description" content="Architecture">
<meta name="keywords" content="">
<meta name="author" content="Sombra">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- inject:fonts:css --><!-- endinject -->
<!-- inject:vendor-styles:css --><link rel="stylesheet" href="../css/vendor-93729a7ec8.css"><!-- endinject -->
<!-- inject:app-styles:css --><link rel="stylesheet" href="../css/main-53180137c4.css"><!-- endinject -->
<!-- uncomment if using your own iconfont -->
<!-- <link rel="stylesheet" href="styles/own-icons.css"> -->
</head>
<body ng-app="selectPopApp" ng-strict-di>
<header>
<header-component></header-component>
</header>
<div class="container">
<div class="row">
<div class="col-lg-12 main-content" ui-view>
</div>
</div>
</div>
</body>
<!-- inject:vendor:js --><script src="../js/vendor-ef1f3e9bbb.js"></script><!-- endinject -->
<!-- inject:app:js --><script src="../js/app-d9c3c6c010.module.js"></script><!-- endinject -->
<!-- inject:scripts:js --><script src="../js/scripts-be58dca5c9.js"></script><!-- endinject -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script src=https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js></script>
</html>
I run the app using Spring-boot, but when I use it in Chrome I get an "Uncaught Syntax Error: Unexpected identifier". The JavaScript that causes the issue is:
import log from './utils/log';
import formatTime from './utils/format-time';
import pluginDefaultOptions from './defaults';
import window from 'global/window';
import videojs from 'video.js';
import WaveSurfer from 'wavesurfer.js';
I tried inserting type="module" into html as suggested in this Q&A, then Chrome stops complaining about the first import-from and gets an error at the "import window from 'global/window' line
Gulp.js used is the following:
(function () {
'use strict';
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var del = require('del');
var express = require('express');
var open = require('open');
var stylish = require('jshint-stylish');
var streamqueue = require('streamqueue');
var runSequence = require('run-sequence');
var merge = require('merge-stream');
var ripple = require('ripple-emulator');
var wiredep = require('wiredep');
var rigger = require('gulp-rigger');
var deletefile = require('gulp-delete-file');
var inject = require('gulp-inject');
var path = {
build: {
html: {
views: 'dist/pages/views/',
components: 'dist/pages/components',
directives: 'dist/pages/directives'
},
js: 'dist/js/',
css: 'dist/css/',
img: 'dist/images/',
fonts: 'dist/fonts/',
icons: 'dist/icons/'
},
src: {
js: 'app/**/*.js',
styles: {
common: 'app/styles/**/*.scss',
views: 'app/views/**/*.scss',
components: 'app/components/**/**/*.scss',
directives: 'app/directives/**/**/*.scss'
},
html: {
views: 'app/views/**/*.html',
components: 'app/components/**/**/*.html',
directives: 'app/directives/**/**/*.html'
},
assets: {
css: 'app/assets/css/**/*.css',
img: 'app/assets/images/**/*.*',
fonts: 'app/assets/fonts/*.*',
icons: 'app/assets/icons/*.*'
}
},
dist: 'dist',
distStatic: '../resources/dist'
};
var resourcesPath = {
fontsScss: 'app/styles/_fonts.scss',
stylesMainSrc: 'app/styles/main.scss',
appModule: 'app/app.module.js',
indexSrc: 'app/index.html',
indexDist: 'dist/pages/index.html',
pagesFolder: '/pages/'
};
/*** Tasks ------------------------------------------------------------------------- ***/
/*** Maintenance ---------------------------------------------- ***/
gulp.task('clean', function (done) {
return del([path.dist], done);
});
gulp.task('clean-static', function (done) {
return del([path.distStatic], {force: true}, done);
});
gulp.task('delete-app-module', function () {
var dest = path.build.js + '*.js';
var regexp = /^app|scripts/;
return gulp.src(dest).pipe(deletefile({
reg: regexp,
deleteMatch: true
}))
});
gulp.task('delete-styles', function () {
var regexp = /^main|fonts/;
return gulp.src([path.build.css + '*.css']).pipe(deletefile({
reg: regexp,
deleteMatch: true
}));
});
/*** Assets --------------------------------------------------- ***/
gulp.task('images', function () {
return gulp.src(path.src.assets.img)
.pipe(gulp.dest(path.build.img));
});
gulp.task('icons', function () {
return gulp.src(path.src.assets.icons)
.pipe(gulp.dest(path.build.icons));
});
gulp.task('fonts', function () {
gulp.src('bower_components/font-awesome/fonts/**.*')
.pipe(gulp.dest(path.build.fonts));
return gulp.src([path.src.assets.fonts, 'bower_components/**/*.{ttf,woff,woff2,eof,svg}'])
.pipe(gulp.dest(path.build.fonts));
});
/*** App files --------------------------------------------------- ***/
gulp.task('styles', ['delete-styles'], function () {
var injectAppFiles = gulp.src(
[
path.src.styles.views,
path.src.styles.components,
path.src.styles.directives,
'!' + resourcesPath.stylesMainSrc
],
{read: false}
);
var injectAppOptions = {
transform: transformFilepath,
starttag: '// inject:app',
endtag: '// endinject',
addRootSlash: false
};
function transformFilepath(filepath) {
return '#import "' + filepath + '";';
}
gulp.src(resourcesPath.fontsScss)
.pipe(plugins.sass({style: 'expanded'}))
.pipe(plugins.rev())
.pipe(gulp.dest(path.build.css));
return gulp.src(resourcesPath.stylesMainSrc)
.pipe(inject(injectAppFiles, injectAppOptions))
.pipe(plugins.sass({style: 'expanded'}))
.pipe(plugins.autoprefixer('last 2 version', '>1%', 'ie 9'))
.pipe(plugins.stripCssComments())
.pipe(plugins.rev())
.pipe(gulp.dest(path.build.css));
});
gulp.task('scripts', ['delete-app-module'], function () {
var dest = path.build.js;
var scriptStream = gulp.src(['**/*.js', '!app.module.js'], {cwd: 'app'})
.pipe(plugins.changed(dest));
gulp.src(resourcesPath.appModule)
.pipe(plugins.rev())
.pipe(gulp.dest(dest));
return streamqueue({objectMode: true}, scriptStream)
.pipe(plugins.ngAnnotate())
.pipe(plugins.concat('scripts.js'))
.pipe(plugins.rev())
.pipe(gulp.dest(dest));
});
gulp.task('html', function () {
gulp.src(path.src.html.views)
.pipe(rigger())
.pipe(gulp.dest(path.build.html.views));
gulp.src(path.src.html.components)
.pipe(rigger())
.pipe(gulp.dest(path.build.html.components));
gulp.src(path.src.html.directives)
.pipe(rigger())
.pipe(gulp.dest(path.build.html.directives));
});
/*** Vendor ---------------------------------------------------- ***/
gulp.task('vendor-js', function () {
var vendorFiles = wiredep().js;
return gulp.src(vendorFiles)
.pipe(plugins.concat('vendor.js'))
.pipe(plugins.rev())
.pipe(gulp.dest(path.build.js));
});
gulp.task('vendor-css', function () {
var vendorStyle = wiredep().css;
return gulp.src(vendorStyle)
.pipe(plugins.concat('vendor.css'))
.pipe(plugins.rev())
.pipe(gulp.dest(path.build.css));
});
/*** Assemble tasks ------------------------------------------- ***/
gulp.task('injector', ['scripts', 'html', 'styles'], function () {
var _inject = function (src, tag) {
return plugins.inject(src, {
starttag: '<!-- inject:' + tag + ':{{ext}} -->',
addRootSlash: false,
ignorePath: path.dist,
addPrefix: '..'
});
};
return gulp.src(resourcesPath.indexSrc)
.pipe(_inject(gulp.src(path.build.css + '/fonts*.css'), 'fonts'))
.pipe(_inject(gulp.src(path.build.css + '/main*.css'), 'app-styles'))
.pipe(_inject(gulp.src(path.build.css + '/vendor*.css'), 'vendor-styles'))
.pipe(_inject(gulp.src(path.build.js + '/vendor*.js'), 'vendor'))
.pipe(_inject(gulp.src(path.build.js + '/app*.js'), 'app'))
.pipe(_inject(gulp.src(path.build.js + '/scripts*.js'), 'scripts'))
.pipe(gulp.dest(path.dist + resourcesPath.pagesFolder));
});
gulp.task('log-success', function () {
console.log('----------------- GULP BUILD SUCCESS --------------------');
});
gulp.task('watchers', function () {
gulp.watch(path.src.assets.css, ['styles', 'injector']);
gulp.watch(path.src.assets.fonts, ['fonts']);
gulp.watch(path.src.assets.img, ['images']);
gulp.watch(path.src.html.views, ['html', 'injector']);
gulp.watch(path.src.html.components, ['html', 'injector']);
gulp.watch(path.src.html.directives, ['html', 'injector']);
gulp.watch(path.src.styles.common, ['styles', 'injector']);
gulp.watch(path.src.styles.views, ['styles', 'injector']);
gulp.watch(path.src.styles.components, ['styles', 'injector']);
gulp.watch(path.src.styles.directives, ['styles', 'injector']);
gulp.watch(path.src.js, ['scripts', 'injector']);
gulp.watch(resourcesPath.indexSrc, ['html', 'injector']);
gulp.watch('bower.json', ['vendor-js', 'vendor-css']);
});
gulp.task('default', function (done) {
runSequence(
'clean',
'clean-static',
[
'fonts',
'images',
'vendor-js',
'vendor-css',
'styles',
'html',
'icons'
],
'injector',
'watchers',
'log-success',
done);
});
gulp.task('deploy', function (done) {
runSequence(
'clean',
'clean-static',
[
'fonts',
'images',
'vendor-js',
'vendor-css',
'styles',
'html',
'icons'
],
'injector',
done);
});
})();
how are you compiling this? Based on your syntax and the names of your compiled modules, I'm assuming you're using either Webpack, which means you're likely using Typescript (unless you meant to tag as AngularJS instead). In any case, ES6 import statements are the same, and the syntax you're using is for default exports only.
import can only be used in ES6 JS if type="module" is on the script tag.
So, unless you're setting default exports and relying on them, the syntax for importing explicit exports is:
import { exportedProperty1 } from 'module-name'
import { exportedThing1, exportedThing2 } from 'module-name'
import defaultExport from 'module-name'
import * as Name from 'module-name'
...where 'module-name' is a relative path to the file.
This syntax does not require type="module":
let myThing = import('module-name')
your issue with window from global/window is going to be specific to your bundler, your platform, your files, and your polyfills.
All the packages that contained es6 JavaScript had to be compiled individually using webpack, then changes had to be made to the "overrides" section of bower.json for the big project to include dist directories and generated min.js files of the compiled projects in order for gulp to inject them. E.g.
"overrides" {
"videojs-record": {
"main": [
"dist/videojs.record.min.js"
]
}
}

Require JS Refress Issue while file access from browser cache

Am using requiredjs. After deployment to the any environment (now screenshot from local) am getting refresh issue. page is not loading properly. I have checked in network tab in firebug. its showing(below image). when the file get 200 OK (BF Cache) status, page not loading properly.
Error:
After giving ctrl+f5
all the pages are coming correctly.
some time i need to give lot of ctrl+f5 then only its working asexpected
my requirejs config file:
require.config({
baseUrl: "../../../../../../../Scripts",
//waitSecond: 0,
//urlArgs : "q="+new Date().getTime(),
enforcedefine: true,
paths: {
//RequireJS Plugins.
'text': 'lib/requirejs/text',
'domReady': 'lib/requirejs/domReady',
'app': 'app',
'noext': 'lib/requirejs/noext',
// Shared Libraries.
'jquery': 'lib/Kendo/jquery.min',
'jqueryMigrate': 'lib/jquery-migrate-1.2.1.min',
'jszip': 'lib/jszip',
'kendo': 'lib/Kendo/kendo.all.min',
'materialize': 'lib/materialize/materialize',
'jqueryValidate': 'jquery.validate.min',
'jsignature': 'lib/jSignature/jSignature.min',
'jqueryMaskedinput': 'lib/jquery/jquery.maskedinput.min',
'jqueryMd5': 'lib/jquery/jquery.md5',
'truckNotifier': 'Controls/serviceTruck.Notifier'
},
shim: {
'app': {
deps: ['kendo']
},
'kendo': {
deps: ['jquery', 'jszip'],
},
'jqueryExtensions': {
deps: ['jquery'],
},
'materialize': {
deps: ['jquery', 'kendo'],
},
'krossRespJs': {
deps: ['jquery'],
},
'jqueryMaskedinput': {
deps: ['jquery'],
},
'truckUploadSelector': {
deps: ['jquery'],
},
'underscore': {
exports: '_'
}
}
});
app.js file:
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([
'domReady!',
'text',
'noext',
'jquery',
'kendo',
'jszip',
'truckNotifier'
], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function (domReady,text,noext,$,kendo,jszip,truckNotifier) {
'use strict';
var app = kendo.observable({
// ---- PUBLIC FIELDS ----
DATE_FORMAT: 'MM/dd/yyyy',
DATE_MASK: '99/99/9999',
DATE_TIME_FORMAT: 'MM/dd/yyyy HH:mm',
DATE_TIME_MASK: '99/99/9999 99:99',
PHONE_MASK: '(999) 999-9999',
TIME_FORMAT: 'HH:mm',
TIME_MASK: '99:99',
$notifier: $('#notify_container'),
router: new kendo.Router(),
isInitialized: false,
/** This call sets up background components of the current page. */
initialize: function () {
var self = this;
// Initialize this first so it can show loading while the rest
// of this module loads.
if (!self.isInitialized) {
$('.link-external').attr('target', '_blank');
$('#notify_container').serviceTruckNotifier();
self.isInitialized = true;
}
window.JSZip = jszip;
},
showPleaseWait: function (show) {
},
/* Pops up a notification at the top of the page. */
notify: function (type, message) {
var types = {
'push': 'notifyPush',
'info': 'notifyInfo',
'success': 'notifySuccess',
'error': 'notifyError',
'warn': 'notifyWarn',
'expired': 'notifyExpired'
};
this.$notifier.serviceTruckNotifier(types[type], message);
}
});
app.initialize();
return app;
}));
script used in View Page:
<script>
require([
'domReady!',
'text',
'noext',
'app',
'jquery',
'jqueryValidate',
'kendo',
'truckNotifier'
],
function (
domReady,
text,
noext,
app,
$,
jqueryValidate,
kendo,
truckNotifier
) {
var notifier = $('#notify_container'),
message = '#(ViewBag.Message)';
$("#primaryTextButton").kendoButton();
$('.all-content').removeClass('dn');
$('.mcenter').addClass('dn');
if (message != "") {
notifier.serviceTruckNotifier("notifyExpired", "#C.LINK_HAS_BEEN_EXPIRED");
}
});
</script>
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/Styles/all/css")
<script src="~/Scripts/lib/requirejs/require.js"></script>
<script src="~/Scripts/config.js"></script>
</head>
<body id="#RenderSection("BodyId", false)">
#{
System.Reflection.Assembly web = typeof(ServiceTruck.Web.Models.ExternalLogin).Assembly;
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(web.Location);
string version = fvi.FileVersion;
System.Reflection.AssemblyName webName = web.GetName();
string myVersion = version.ToString();
ViewBag.Version = myVersion;
}
#RenderSection("featured", required: false)
<section class="container-fluid">
#RenderBody()
</section>
<!-- Service Truck Layout Footer Start -->
<footer class="copy-right">
<div class="col-md-6 text-left">
<p>All rights reserved.</p>
<p>Copyright © 2016 Name.</p>
</div>
<div class="col-md-6 text-right">
<p>Build #myVersion</p>
<p>Recommended Browsers: Internet Explorer 11, Firefox 48, Chrome 52</p>
</div>
</footer>
<!-- Service Truck Layout Footer End -->
#RenderSection("scripts", required: false)
</body>
</html>
One thing that is definitely wrong with your configuration is the shim for app:
'app': {
deps: ['kendo']
},
Your app module is an AMD module: it calls define. So you cannot use a shim for it. Setting a shim for a module that cannot benefit from one can lead to undefined behavior.
I've run experiments with this at times and got inconsistent results from one version of RequireJS to the next. The point is that setting a shim for an AMD module has no defined semantics.

Angular 2 TypeError: Cannot read property 'animate' of null

I'm using Chrome 51 and Angular 2.rc4 and following errors popup in the console when loading my angular app.
TypeError: Cannot read property 'animate' of null
at e.supportsWebAnimation (platform-browser.umd.js:2232)
at st (platform-browser.umd.js:2896)
at t._instantiate (core.umd.js:6370)
at t._instantiateProvider (core.umd.js:6311)
at t._new (core.umd.js:6300)
at t.getObjByKeyId (core.umd.js:5954)
at t._getByKeyDefault (core.umd.js:6480)
at t._getByKey (core.umd.js:6452)
at t._getByReflectiveDependency (core.umd.js:6442)
at t._instantiate (core.umd.js:6342)
at c (vendors.js:3)
at vendors.js:3
at t.invokeTask (vendors.js:3)
at Object.onInvokeTask (core.umd.js:9091)
at t.invokeTask (vendors.js:3)
at t.runTask (vendors.js:3)
at s (vendors.js:3)
at XMLHttpRequest.invoke (vendors.js:3)
If i refresh it again it disappears and the app loads fine. When i dig into it a bit more, i found out the following problematic code where the body of the document seems to be null in file platform-browser.umd.js.
BrowserDomAdapter.prototype.supportsWebAnimation = function () {
return isFunction(document.body['animate']);
};
I am using systemjs-builder for bundline the angular components, like so:
//Bundle auth module to a single script file
gulp.task('bundle_auth', ['bundle_vendors'], function() {
var builder_auth = new Builder('', 'assets/js/dependencies/config/auth.system.js');
return builder_auth
.buildStatic('assets/app/auth/main.js', 'assets/dist/js/auth/bundle.js', { minify: true, sourceMaps: true })
.then(function() {
//console.log('Build complete for auth module');
})
.catch(function(err) {
console.log(err);
});
});
And here is my systemjs config, if needed:
(function(global) {
// map tells the System loader where to look for things
var map = {
'app' : 'assets/app/auth',
'#angular': 'node_modules/#angular',
'ng2-translate': 'node_modules/ng2-translate',
'rxjs': 'node_modules/rxjs', // added this map section
'primeng': 'node_modules/primeng',
'angular2-recaptcha': 'node_modules/angular2-recaptcha'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'assets/app/auth/main.js', defaultExtension: 'js'},
'rxjs': { defaultExtension: 'js' },
'primeng': {defaultExtension: 'js'},
'angular2-recaptcha': {defaultExtension: 'js'}
};
var packageNames = [
'common',
'compiler',
'core',
'http',
'forms',
'platform-browser',
'platform-browser-dynamic',
'router'
];
// Individual files (~300 requests):
function packIndex(pkgName) {
packages['#angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['#angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
}
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
packageNames.forEach(setPackageConfig);
var config = {
defaultJSExtensions: true,
map: map,
packages: packages
};
System.config(config);
})(this);
This issue only happens in chrome.
EDIT
Here is the angular bootstrap file:
import {bootstrap} from '#angular/platform-browser-dynamic';
import {AppComponent} from './component/app.component';
import {HTTP_PROVIDERS} from '#angular/http';
import {HttpService} from '../common/service/http.service';
import {enableProdMode} from '#angular/core';
import {disableDeprecatedForms, provideForms} from '#angular/forms';
import {APP_ROUTER_PROVIDERS} from '../routes/auth.routes';
import {TRANSLATE_PROVIDERS, TranslateService, TranslatePipe, TranslateLoader, TranslateStaticLoader} from 'ng2-translate/ng2-translate';
enableProdMode();
bootstrap(AppComponent,[
APP_ROUTER_PROVIDERS,
HTTP_PROVIDERS,
TRANSLATE_PROVIDERS,
HttpService,
disableDeprecatedForms(),
provideForms()
]).catch(err => console.error(err));
I think you include your bundled js files inside of the head section in the index.html but you should transfer those to the body part under your app.
For being more clear after i transfered my application to webpack i had exactly same issue.
For example,
<!DOCTYPE html>
<html>
<head>
<base href="">
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="prod/vendor.js"></script>
<script src="prod/app.js"></script>
</head>
<body>
<app-one>
Loading...
</app-one>
</body>
</html>
I transferred scripts like this
<!DOCTYPE html>
<html>
<head>
<base href="">
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<app-one>
Loading...
</app-one>
<script src="prod/vendor.js"></script>
<script src="prod/app.js"></script>
</body>
</html>

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
})

Categories

Resources