App takes too long to load in production - javascript

I have pushed my angular 2 app on heroku but it takes too long to load.
is there a way to bundle everything up because right now i have this in my index.html
<html>
<head>
<base href="/">
<title>Angular 2 Arc</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<ng2-app>Loading...</ng2-app>
<!-- Load Angular 2 Core libraries -->
<script src="es6-shim/es6-shim.min.js"></script>
<script src="systemjs/dist/system-polyfills.js"></script>
<script src="angular2/bundles/angular2-polyfills.js"></script>
<script src="systemjs/dist/system.src.js"></script>
<script src="rxjs/bundles/Rx.js"></script>
<script src="angular2/bundles/angular2.dev.js"></script>
<script src="angular2/bundles/router.dev.js"></script>
<script src="angular2/bundles/http.js"></script>
<!-- Load Bootstrap and Jquery -->
<script src="lib/jquery/jquery.min.js" charset="utf-8"></script>
<script src="lib/bootstrap/js/bootstrap.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css">
<!-- Configure SystemJS -->
<script>
System.config({
defaultJSExtensions: true,
packages: {
boot: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('js/boot')
.then(null, console.error.bind(console));
</script>
</body>
</html>
My setup is express server and system JS.
server.js
var express = require('express');
var bodyParser = require('body-parser')
var fs = require("fs");
// initialize express
var app = express();
// declare build and node_module paths
app.use(express.static("./build"));
app.use(express.static("./node_modules/"));
// parse request body
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var body;
// route to send json data from angular 2
app.post('/export', function(req, res){
body = req.body;
res.json("Got the data!");
fs.writeFile('parameters.json', JSON.stringify({body}, null, 4), function (err) {
if (err) return console.log(err);
console.log('Data json file created!');
});
});
// start server
app.listen(process.env.PORT || "3001", function(){
console.log("Express server running on localhost:3001");
});

If its the free heroku tier its probably because its sleeping when you request it?
You can minify and concatenate your js files to decrease load times.
Here is a guide on how to do that with gulp tasks:
https://caveofcode.com/2016/03/gulp-tasks-for-minification-and-concatenation-of-dependencies-in-angularjs/

Related

Hosting a Vue.js app on a Node.js Express - on cPanel - only loading index.html

I'm hosting a Vue.js app on a Node.js Express app which works perfectly when running locally. When I upload it to cPanel, it only loads the index.html leaving me with a blank page and several 404 errors for all the "missing" files which are sitting next to it.
NODE: app.js
const express = require("express");
const cors = require("cors");
const path = __dirname + '/client';
const app = express();
app.use('/', express.static(path));
app.use(cors({ origin: '*' }));
app.get('/test', function (req, res) {
res.send("API TEST!");
});
// set port, listen for requests
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
NODE: package.json
{
"name": "basic_node_app",
"version": "1.0.0",
"description": "A Basic Node App to serve something.",
"main": "app.js",
"author": "",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1"
}
}
VUE: index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="/favicon.ico">
<title>basic_vue_app</title>
<link href="/js/app.62f5dd50.js" rel="preload" as="script">
<link href="/js/chunk-vendors.2b964eb5.js" rel="preload" as="script">
</head>
<body><noscript><strong>We're sorry but basic_vue_app doesn't work properly without JavaScript enabled. Please enable it
to continue.</strong></noscript>
<div id="app"></div>
<script src="/js/chunk-vendors.2b964eb5.js"></script>
<script src="/js/app.62f5dd50.js"></script>
</body>
</html>
VUE: App.vue
<template>
<div>
<label>THIS IS A GOOD TEST</label>
<label>API WORKS -> {{ apiresult }}</label>
</div>
</template>
<script>
import Axios from "axios";
export default {
name: "App",
data() {
return {
apiresult: "",
};
},
mounted() {
Axios.get("/test").then((res) => {
this.apiresult = res.data;
});
},
};
</script>
<style>
</style>
VUE: dist folder
JS folder
app.[id].js
app.[id].js.map
chunck-vendors.[id].js
chunck-vendors.[id].js.map
favicon.ico
index.html
on my cPanel, this is my structure:
image1
I'm running the node app like this:
image2
Finally, my problem. When I run it locally I get this on my browser:
image3
But when I deploy it and run it on cPanel I get:
image4
Thanks in advance for all your help.
Best regards,

How do I link a JavaScript file to HTML in Express?

I’m running a NodeJS server with Express, using Handlebars as the engine.
app.use(express.static(publicDirPath))
(...)
app.engine("hbs",hbs({
extname: "hbs",
defaultView: "main",
layoutsDir: path.join(srcDirPath, "views/layouts"),
partialsDir: path.join(srcDirPath, "views/partials"),
}));
(...)
app.listen(3000, () => {
console.log("Server started at port 3000.");
});
I have a login page:
app.get("/Login", (req, res) => {
res.render("Login", { layout: "Loginlayout" });
});
app.get("/public/js/login.js", (req, res) => {
res.header("Content-Type", "application/javascript")
res.end();
});
– which is using this header:
<head>
<script src="/public/js/login.js" async></script>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="css/login.css">
<title>Login</title>
</head>
– but I cannot use any of the functions from in login.js.
I also got some "MIME type (“text/html”) mismatch" errors, but I think I fixed them by using
res.header("Content-Type", "application/javascript")
– but I still can’t use any of the functions. I also tried multiple browsers, but nothing worked.
Let app.use(express.static(publicDirPath)) play it's role. Move local js/css file under publicDirPath dir, the express will serve assets' path for you.

Angular is not defined Gulp.js

I still have this error Angular is not defined. Im 99.9999% Sure its something to do with the paths not being confugred properly, but im out of clue. I cant fix it! This is my folder structure as of now:
bower_components/
node_modules/
app/
components/
home/
controller/
homeCtrl.js
css/
home.css
home.html
shared/
css/
directives/
filters/
directives/
sass/
services/
assets/
audio/
debug/
dist/
app.min.js
vendor.min.js
lib/
etc...
gulp/
paths.js
gulpfile.js
index.html
etc....
It for some reason says angular is not defined.
Gulpfile.js:
//Require Gulp
var gulp = require("gulp");
var ngAnnotate = require("gulp-ng-annotate");
var uglify = require("gulp-uglify");
var concat = require("gulp-concat");
var sourceMaps = require("gulp-sourcemaps");
var util = require('gulp-util');
var coffee = require("gulp-coffee")
var clean = require("gulp-clean");
var expect = require('gulp-expect-file');
var sass = require('gulp-sass');
var es = require('event-stream');
var ng_annotate = require('gulp-ng-annotate')
var base = 'app';
// var minifyCss = require('gulp-minify-css');
var paths = require("./gulp/paths");
//remove temporary directories like dist
gulp.task('clean', function() {
return gulp.src('assets/dist', {read: false})
.pipe(clean());
});
// combines all js files into one and create sourcemaps for them
gulp.task('scripts', function(done) {
gulp.src(paths.js)
.pipe(sourceMaps.init())
.pipe(concat('app.min.js'))
.pipe(ngAnnotate())
.pipe(uglify().on('error', util.log))
.pipe(sourceMaps.write('.'))
.pipe(gulp.dest(paths.dest))
.on('error', util.log)
.on('end', done);
});
gulp.task('copy', function() {
var files = ['bower_components/angular/angular.min.js'];
return gulp.src(files)
.pipe(expect(files))
});
gulp.task('watch', function() {
gulp.watch(paths.js, ['scripts'])
});
gulp.task('scripts:vendor', function() {
return gulp.src(paths.vendor_js)
// .pipe(concat(paths.vendor_js[0]))
.pipe(concat('vendor.min.js'))
.pipe(uglify().on('error', util.log))
.pipe(gulp.dest(paths.dest));
});
gulp.task('serve', function() {
})
gulp.task('default', function() {
console.log("running gulp");
});
gulp/Paths.js:
module.exports = {
dest: 'assets/dist',
js: [
'app/app.module.js',
'app/app.run.js',
'app/shared/**/*.module.js',
'app/shared/**/*.js',
'app/components/**/*.js',
'app/components/**/*.module.js'
],
sass: ['app/shared/**/*.sass'],
vendor_js: [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.min.js',
'bower_components/**/*.min.js',
'assets/lib/svg-assets-cache/svg-assets-cache.js',
'assets/lib/alertifyjs/build/alertify.min.js',
'assets/lib/Recaptcha/googleRecaptchaAPI.js',
'assets/lib/angular-screenfull/angular-screenfull.min.js',
'assets/lib/screenfull/screenfull.min.js',
'assets/lib/angular-selectize/angular-selectize.js'
],
vendor_styles: [
'bower_components/selectize/dist/css/selectize.css',
'bower_components/font-awesome/css/font-awesome.min.css',
'assets/lib/alertifyjs/build/css/alertify.css',
'assets/lib/alertifyjs/build/css/themes/semantic.min.css',
'bower_components/vex/css/vex.css',
'bower_components/vex/css/vex-theme-flat-attack.css',
'assets/lib/material-charts/material-charts.min.css'
]
};
index.html:
<!DOCTYPE html>
<html lang="en" class="html_container">
<head>
<meta charset="UTF-8">
<!--<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">-->
<meta name="viewport" content="width=1200">
<title>Ng-Forum</title>
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css" />
<link rel="stylesheet" href="assets/lib/alertifyjs/build/css/alertify.css" />
<link rel="stylesheet" href="assets/lib/alertifyjs/build/css/themes/semantic.min.css" />
<link rel="stylesheet" href="bower_components/vex/css/vex.css" />
<link rel="stylesheet" href="bower_components/vex/css/vex-theme-flat-attack.css" />
<link rel="stylesheet" href="https://cdn.rawgit.com/amanuel2/MathGame/master/chartjs/material-charts.min.css" type="text/css" />
<link rel="stylesheet" href="bower_components/angular-material/angular-material.css" />
<link rel="icon" href="favicon.ico">
</head>
<body ng-app="ForumApp">
<div ui-view></div>
<!--<script type="text/javascript" src="https://code.angularjs.org/1.4.9/angular.js"></script>-->
<script type="text/javscript" src="assets/dist/vendor.min.js"></script>
<script type="text/javascript" src="assets/dist/app.min.js"></script>
</body>
</html>
Help would be greatly appreciated here! Btw im working it on Cloud9IDE So if we could fix it there, it would be quick and fantastic! https://ide.c9.io/amanuel2/ng-fourm
The reason was that i mispelled javascript:
<script type="text/javscript" src="assets/dist/vendor.min.js"></script>
It was preety hard to find because, something that simple can completely throw you off!

Mochai Chai test not running

I'm learning app testing at the moment, using this course: https://code.tutsplus.com/courses/angularjs-for-test-driven-development/
I'm on lesson 2.3 where we have Mocha and Chai installed, a test folder with main.spec.js setup and gulp task setup to serve the app and tests.
When he updated his main.spec.js file with this simple describe statement:
describe('The Address Book App', function() {
it ('should work', function() {
chai.assert.isArray([]);
});
});
It ran fine for him:
However here is my setup:
test/main.spec.js
describe('The Dashboard app', function() {
it ('should work', function() {
chai.assert.isArray([]);
});
});
Basic markup:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mocha Spec Runner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="../app/favicon.ico">
<link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
<link href="testing.css" rel="stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../bower_components/mocha/mocha.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="../bower_components/chai/chai.js"></script>
<script>
mocha.run();
</script>
<script src="main.spec.js"></script>
</body>
</html>
However my test file isn't displaying my first test:
Gulpfile setup, same as the authors, cept PORT numbers are different:
gulp.task('serve', function() {
browserSync.init({
notify : false,
port : 3333,
server: {
baseDir: ['app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
gulp.task('serve-test', function() {
browserSync.init({
notify : false,
port : 4444,
server: {
baseDir: ['test', 'app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
Any idea why my first basic test isn't running?
Everything looks right except the ordering.
Just swap the
<script>
mocha.run();
</script>
with
<script src="main.spec.js"></script>
You want to run mocha at the end when all your specs and setup is done.

AngularJS UI Router reload not working

I have two states in my current apps, which is login and register. If I just open my website towards localhost:8001, it is automatically redirect to /login because I've set
$urlRouterProvider.otherwise('/login')
But if I open my website towards localhost:8001/asdf, it does not redirect to /login. It just print not found.
What am I missing?
Here is my full code
app.module.js
var myApp = angular.module('myApp', ['routesApp']);
app.routes.js
var routesApp = angular.module('routesApp', ['ui.router','loginApp']);
routesApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/login');
$locationProvider.html5Mode(true);
}]);
login.routes.js
routesApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'app/components/login/login.html',
controller: 'loginController'
});
});
register.routes.js
routesApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('register', {
url: '/register',
templateUrl: 'app/components/register/register.html',
});
});
login.controller.js
var loginApp = angular.module('loginApp', ['ngAnimate']);
loginApp.config(function($sceDelegateProvider, $httpProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self'
])
});
var loginController = function($scope){
//test controller
}
loginApp.controller('loginController', loginController);
index.html
<!DOCTYPE html>
<html>
<head>
<title>MyApp</title>
<base href="/">
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CSS -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<link href="assets/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet/less" type="text/css" href="assets/less/phinisi.less">
<link rel="stylesheet/less" type="text/css" href="assets/less/dropdown.less" />
<!-- JavaScript -->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="bower_components/angular-animate/angular-animate.min.js"></script>
<script src="assets/js/angular-payments.js"></script>
<script src="assets/js/jquery-2.1.3.min.js"></script>
<script src="assets/js/bootstrap.js"></script>
<script src="assets/js/ui-bootstrap-0.12.1.min.js"></script>
<script src="app/app.module.js"></script>
<script src="app/app.routes.js"></script>
<!-- Login Script -->
<script src="app/components/login/login.controller.js"></script>
<script src="app/components/login/login.routes.js"></script>
<!-- Register Script -->
<script src="app/components/register/register.routes.js"></script>
<script src="assets/js/less.js"></script>
</head>
<body ng-app="myApp">
<div ui-view></div>
</body>
</html>
The problem is that you are using html5mode but it appears your server is not set to properly forward requests to your index for Angular to handle.
The server is attempting to find a resource at this location and failing. The reason this did not happen previously, is because the # that is present when html5mode is disabled causes the browser to recognize that the rest of the URL is not a navigable path. The path prior to the # is your index.html file, where Angular exists and knows to handle routing based on the proceeding URI path.
Since I'm not sure what server you are running on, I can't provide a specific answer, but this link provides answers for many of the commonly used servers:
How to: Configure your server to work with html5Mode
Please note, you'll need to make the change in your local build too. Here's an example using grunt with grunt-contrib-connect and connect-modrewrite
connect: {
options: {
hostname: 'localhost',
port: 8001,
middleware: function (connect, options) {
var modRewrite = require('connect-modrewrite');
var middlewares = [
modRewrite(['^[^\\.]*$ /index.html [L]'])
];
options.base.forEach(function (path) {
middlewares.push(connect.static(path));
});
return middlewares;
}
}
}
What this does is tells the server to route ALL requests back to index.html so that Angular can process the routing.

Categories

Resources