Splitting all.js into multiple files - Angular JS - angularjs

I have been working on an Angular JS based application. I have written a set of gulp commands to uglify/remove comments from JS code. When I run the web application and monitor the network traffic, I noticed that minified(uglified) 'all.js' file consumes quite a lot of time to be loaded (please forget about the caching).
I believe that splitting the all.js file (before or after processing) in to several pieces (let's say four pieces) will improve the application loading time. Please mention if you think there is/are better way(s).
Still I am struggling to find a way to get an approach to above mentioned method under #1. Still no luck :-( Please advice me.
Gulpfile
// include plug-ins
'use strict';
var gulp = require('gulp');
var concat = require('gulp-concat');
var htmlbuild = require('gulp-htmlbuild');
var plugins = require('gulp-load-plugins')();
var es = require('event-stream');
var clean = require('gulp-clean');
var uglify = require('gulp-uglify');
var strip = require('gulp-strip-comments');
var pump = require('pump');
// pipe a glob stream into this and receive a gulp file stream
var gulpSrc = function (opts) {
var paths = es.through();
var files = es.through();
paths.pipe(es.writeArray(function (err, srcs) {
var fixedFiles = [];
for (var i=0; i < srcs.length; i++)
{
fixedFiles[i] = srcs[i].replace("~", ".");
console.log(fixedFiles[i]);
}
gulp.src(fixedFiles, opts).pipe(files);
}));
return es.duplex(paths, files);
};
var jsBuild = es.pipeline(
plugins.concat('all.js'),
gulp.dest('./Scripts/')
);
gulp.task('clean', function () {
return pump(gulp.src('./Scripts/all.js')
.pipe(clean({ force: true })));
});

Related

My gulp.js file is only running the first time and then it won't watch

I made a gulp.js file that is meant to be observing my changes and rebuilding so that my react code can update after the scss gets converted to css with each change. Here's what I have:
'use strict';
//dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var changed = require('gulp-changed');
//////////////
// - SCSS/CSS
//////////////
var SCSS_SRC = './src/assets/scss/**/*.scss';
var SCSS_DEST = './src/assets/css';
// Compile SCSS
gulp.task('compile_scss', function(){
gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(rename({ suffix: '.min'}))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
});
//detect changes in SCSS
gulp.task('watch_scss', function(){
gulp.watch(SCSS_SRC, gulp.series('compile_scss'));
});
//Run tasks
gulp.task('default', gulp.series(['watch_scss'], function(){
}));
This is the first time I do this but from what I can tell it is correct. There's no error being thrown and it works sometimes. However, when I make 2 changes to my default.scss file, the 1st one gets converted to css but for the second one I need kill the task and run gulp again. What might I be missing?

Why are the same comments showing up on multiple pages in AngularJs 1.5

I've tried the following code on different pages like about, services with appropriate URL and identifier. But I get the same comments on both pages. I'm using Angular 1.5. I've added this to the corresponding controller.
var disqus_config = function () {
// About us
this.page.url = "http://localhost/#!/about";
this.page.identifier = "about";
// For Services Page
//this.page.url = "http://localhost/#!/services";
//this.page.identifier = "services";
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://smetest.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
Can anyone help with this?

Getting Error message "RegistrationPO is not a constructor" on log using Protractor

When i am executing my spec file(given below) ,I am getting the error message "RegistrationPO is not a constructor" ,Plz help me to solve my query.Thanks in advance.
//Registration_spec//
'use strict';
var FunLib = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Function_Lib.js'); //Write the location of your javascript file
var RegistrationPO = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Registration_PO.js'); //Write the location of your javascript file
var testData = require('./FFtestdata_Dev_p.json');
describe('Registration: ', function() {
var FuncLib;
var Registration;
var URL;
var EC = protractor.ExpectedConditions;
FuncLib = new FunLib();
Registration = new RegistrationPO();
beforeEach(function () {
browser.ignoreSynchronization = true;
});
//Scenario 1: Open browser :working
it('1-Open the web browser',function(){
browser.ignoreSynchronization = true;
browser.get('Http://dev.forfirm.com:3000');
browser.sleep(200000);
});
});
var FunLib = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Function_Lib.js'); //Write the location of your javascript file
var RegistrationPO = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Registration_PO.js'); //Write the location of your javascript file
Why do you trying to find your pageObjects in node_modules/protractor?
With this you will lose everything on every node_modules reinstall.
I believe this is the reason why you getting errors - you cant import, because file does not exist there
Create more plain structure, something like
node_modules/...all your dependencies will be installed here
utils/Function_Lib.js
pageobjects/Registration_PO.js
specs/registration.spec.js
package.json
protractor.config.js
Then your imports in specs/registration.spec.js will be something like this:
var FunLib = require('../utils/Function_Lib.js');
var RegistrationPO = require('../pageobjects/Registration_PO.js');
Also check what you are exporting in Registration_PO.js and Function_Lib.js

AngularJs - get list of all registered modules

Can I get a list of all registered modules at run time?
For example:
// Some code somewhere in some .js file
var module1 = angular.module('module1', []);
// Some code in some other .js file
var module2 = angular.module('module2', []);
// Main .js file
var arrayWithNamesOfAllRegisteredModules = .....
// (result would be: ['module1', 'module2'])
Angular does not provide a way to retrieve the list of registered modules (at least I was not able to find a way in source code). You can however decorate angular.module method to store names in array. Something like this:
(function(orig) {
angular.modules = [];
angular.module = function() {
if (arguments.length > 1) {
angular.modules.push(arguments[0]);
}
return orig.apply(null, arguments);
}
})(angular.module);
Now you can check angular.modules array.
Demo: http://plnkr.co/edit/bNUP39cbFqNLbXyRqMex?p=preview
You can simply do :
console.log(angular.module('ModuleYouWantToInspect').requires);
It should return of an array of strings (dependencies). You can do the same for the output.
Given an angular.element, the $injector.modules array contains the list of registered modules.
e.g.
angular.element(document.body).injector().modules
If you're debugging, I discovered you can get the list by:
Find or add code to invoke run() from any module with any body, say:
angular.module('myModule')
.run(function() {})
Put a breakpoint on the .run, and step into angular.run(). There's an object called "modules" in scope that has all the modules as properties, by name.
This may work with other module methods too, or be accessible from code; I haven't tried very hard to understand the larger picture.
Improving solution
(function(angular) {
var orig = angular.module;
angular.modules = [];
angular.modules.select = function(query) {
var cache = [], reg = new RegExp(query || '.*');
for(var i=0,l=this.length;i< l;i++){
var item = this[i];
if(reg.test(item)){
cache.push(item)
}
}
return cache;
}
angular.module = function() {
var args = Array.prototype.slice.call(arguments);
if (arguments.length > 1) {
angular.modules.push(arguments[0]);
}
return orig.apply(null, args);
}
})(angular);
Now you can select modules:
angular.modules.select('app.modules.*')
Creating modules tree:
var app = angular.module('app.module.users', ['ui.router'...]);
var app = angular.module('app.module.users.edit', ['app.modules.users']);
Your main module app (concat submodules)
angular.module('app', ['ui.bootstrap', 'app.services', 'app.config']
.concat(angular.modules.select('app.module.*')));
in addition to #dfsq answer you can get list of modules with it dependencies
var AngularModules = (function (angular) {
function AngularModules() {
extendAngularModule();
angular.element(document).ready(function () {
getModulesDependencies();
});
}
var extendAngularModule = function () {
var orig = angular.module;
angular.modules = [];
angular.module = function () {
var args = Array.prototype.slice.call(arguments);
var modules = [];
if (arguments.length > 1) {
modules.push(arguments[0]);
}
for (var i = 0; i < modules.length; i++) {
angular.modules.push({
'module': modules[i]
});
}
return orig.apply(null, args);
};
};
var getModulesDependencies = function () {
for (var i = 0; i < angular.modules.length; i++) {
var module = angular.module(angular.modules[i].module);
angular.modules[i].dependencies = module && module.hasOwnProperty('requires') ? module.requires : [];
}
};
return AngularModules;
})(angular);
Usage:
var modules = new AngularModules();
There is a similar question with better answers here https://stackoverflow.com/a/19412176/132610, a summary of what they proposed is:
var app = angular.module('app', []);
# app.service(/**your injections*/) etc
# to access to the list of services + injections
app._invokeQueue #has following form:
[
[
'$provide',
'service',
Arguments[
'serviceName',
[
'$dependency1',
'$dependency2',
function(){}
],
]
]
]
This involves poking at implementation details that may change over time, but you can try this.
Load the page fully.
Set a breakpoint inside angular.module().
Call angular.module() from the console.
When you hit the breakpoint execute print out the modules dictionary console.dir(modules) or if you want to copy it into another editor window.prompt('', JSON.stringify(modules))
This works because behind the scenes angular builds a dictionary of the loaded modules called modules. You also want to wait until it's finished loading all the modules so they're in the dictionary.

Can I apply Flux architecture with ReactJS.net?

How create flux architecture in asp.net using reactjs.net ?
I will have several files. Jsx, how will I manage to be all rendenizador by the server?
In this example => Link, it creates using asp.net but not render with server
I am currently working on a feature as a test bed for reactjs + flux in our .net application. Here is how it is set up.
We use nodejs as a package manager. we use NodeJs Visual Studio Tools to get the nodejs interactive window in VS and to be able to create NodeJs projects. http://nodejstools.codeplex.com/
Gulp task calls browserify to search through the the root jsx and find all dependencies. Gulp also calls the reactify library is used to transform the jsx files. The concatenated .js file is put on in a directory in our mvc website.
Gulp task copies all relevant js files to the mvc.net project as well.
When developing we use the Visual Studio Task Runner extension to run a Gulp task that watches for changes so we don't have to "keep building" while developing. It uses the "watchify" library.
We use Jest for testing - although we had an issue with NodeJs and jest playing nice in the newest version of NodeJs, so we had to down grade to 0.10.36.
we use TeamCity to run the Gulp task before building our solution (have a test setup, but haven't added it to my new feature yet).
Gulp does most of the magic. Here is a copy of our Gulp file (it is messy, but I am still learning). Many of the tasks are to watch css js and jsx files, but I hope this helps.
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var concat = require('gulp-concat');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var createbundler = function () {
var bundler = browserify({
entries: ['./app/js/VaeApp.jsx'], // Only need the root js file, browserify finds the dependencies
transform: [reactify], // We want to convert JSX to normal javascript
debug: false, // include sourcemapping for minified scripts?
cache: {}, packageCache: {}, fullPaths: true // Requirement of watchify
});
return bundler;
}
gulp.task('js', function () {
var bundler = createbundler();
bundler.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())// <----- convert from streaming to buffered vinyl file object
.pipe(uglify())
// Create the initial bundle when starting the task
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
});
gulp.task('js-shim-sham', function () {
gulp.src('./node_modules/es5-shim/es5-*.min.js')
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
console.log("updated shim-sham");
});
gulp.task('js-dev', function () {
var watcher = watchify(createbundler());
return watcher
.on('update', function () { // When any files update
var updateStart = Date.now();
console.log('Updating!');
watcher.bundle().pipe(source('bundle.js'))
.pipe(buffer())// <----- convert from streaming to buffered vinyl file object
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
})
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())// <----- convert from streaming to buffered vinyl file object
// .pipe(uglify())
// Create the initial bundle when starting the task
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
});
var runcss = function () {
var updateStart = Date.now();
gulp.src('./app/css/document/*.css')
.pipe(concat('main.css'))
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/css'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
};
var runimages = function () {
var updateStart = Date.now();
gulp.src('./app/img/*.*')
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/img'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
};
gulp.task('styles', function () {
runcss();
runimages();
});
gulp.task('styles-dev', function () {
runcss();
gulp.watch('./app/css/document/*.css', runcss);
runimages();
gulp.watch('./app/img/*.*', runimages);
});
// Just running the two tasks
gulp.task('build-dev', ['js-dev', 'styles-dev', 'js-shim-sham']);
// Just running the two tasks
gulp.task('build', ['js', 'styles', 'js-shim']);
Check out react-dot-not.
It uses webpack/gulp with ASP.MVC. it supports redux/flux, supports client side routing with react-router, with an F5 at any time to re-render the same page from the server.

Resources