Setting up Angular Universal App for development - node.js

I have created a project with Angular-CLI. (using command: ng new my-angular-universal).
Then I carefully followed all the instructions from https://github.com/angular/angular-cli/wiki/stories-universal-rendering
It builds for --prod and works fine. But there are no instructions on how I can set up a --dev build and have it served with --watch flag.
I tried removing --prod flags from npm "scripts", and it doesn't even run in dev mode. It builds fine but when I open it in browser this is what I see (directly printed to response):
TypeError: Cannot read property 'moduleType' of undefined
at C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:7069:134
at ZoneDelegate.invoke (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:105076:26)
at Object.onInvoke (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:6328:33)
at ZoneDelegate.invoke (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:105075:32)
at Zone.run (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:104826:43)
at NgZone.run (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:6145:69)
at PlatformRef.bootstrapModuleFactory (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:7068:23)
at Object.renderModuleFactory (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:52132:39)
at View.engine (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:104656:23)
at View.render (C:\Users\Mikser\documents\git\my-angular-universal\dist\server.js:130741:8)
the versions of npm packages that I use are currently the latest:
#angular/* - #5.2.*
#angular/cli #1.7.3
except for ts-loader, had to downgrade it because it wasn't working:
ts-loader #3.5.0
So if anyone has any info on how to make this work, it would be very appreciated! Or maybe you know some project templates with Angular Universal App configured for both --dev and --prod builds and ability to --watch?

For development, run npm run start which triggers ng serve. The current setup has hot module reloading so it will watch for your changes and update your dev view. I used the same instructions and got it working here https://github.com/ariellephan/angular5-universal-template
In short, for development, run npm run start and look at http://localhost:4200.
For production, run npm run build:ssr and npm run serve:ssrand look at http://localhost:4000

As contributors have pointed out, it might not be the most efficient and fastest way to develop, but nevertheless I did not want to accept workarounds. Besides, hosting front and back on separate servers brings up CORS issues, and I never planned my app to run on separate hosts, I wanted it all on the same host together with API methods.
The problem with --dev build was this:
when building with the following command:
ng build --app 1 --output-hashing=false (note that there is no --prod flag)
AppServerModuleNgFactory turned out missing in the ./dist-server/main.bundle
I imagine that this relates to the ahead of time(--aot) compilation which is the default behavior if you are building for --prod. So the instructions from https://github.com/angular/angular-cli/wiki/stories-universal-rendering included instructions to configure express server for production build only. And since there is no need for server to be able to dynamically render html templates the working --dev build command would be:
ng build --app 1 --output-hashing=false --aot
and this gets rid of the TypeError: Cannot read property 'moduleType' of undefined
Now to watch this whole mess:
run these in separate command windows:
ng build --watch
ng build --app 1 --output-hashing=false --aot --watch
webpack --config webpack.server.config.js --progress --colors --watch
And for the server to restart on change, you have to install nodemon package and run it like this:
nodemon --inspect dist/server (--inspect if you wish to debug server with chrome)
Some other important stuff:
Angular/CLI has a command to generate necessary scaffolding for a universal app:
ng generate universal
and it generates a fixed version of main.ts that avoids client angular bootstrap issue:
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
});
a problem that I stumbled upon once I implemented TransferState

There are basically two parts - the server and the UI. While developing the UI, I simply use ng serve. That means when I make changes in my code in the IDE, the browser refreshes automatically. And, here the server part is not used.
I do prod build and run the server only for final testing to see if everything works as expected (No error due to any 3PP library DOM manipulation or AOT related issues, etc.)
Here, I have created a skeleton structure of an Angular Universal project. As I extensively use Vagrant and Docker in my projects, I run the server in a Docker container within the Vagrant guest system. And for development of the UI, I don't run the server. Simply, the ng serve is used.
If you look into my structure in the above Github link, you'll find the details as to how to run it for development and production in the Readme file.

The web server handler server.ts uses the server bundle
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');
That's why the server bundle needs to be compiled before you can compile the server.ts file.
So having a watch system would mean
watching/recompiling the client bundle
watching/recompiling the server bundle
recompiling the server.ts once the server bundle is created
All of them take some time (especially if you do it with aot)
I'd recommend, like Saptarshi Basu mentionned, to develop as best as you can with ng serve and check with angular universal every so often.
Otherwise, it should be possible do achieve what you want with some kind of tasks (grunt/gulp/...) which triggers sequentially ng build ... and recompilation of server.ts file.

It is a bit messy no doubt, as we preferably wish for one command to rule them all.
I came up with a somewhat OK solution where my output will be:
dist/browser
dist/ng-server
Using the executable npm-run-all package (I find it working a lot better on windows machines than concurrently does) I run the three watch tasks: browser, ng-server and nodeJS. Watching node has a pre-task defined that simply runs a small utility/helper/file that watches for the existence of a dist/ng-server folder and terminate itself once found.
For all of this to work (based on the universal-starter repo as of november 2018) there's a couple of modifications to package.json required. Primarily, to support the --watch flag on ng run commands we need to update the compiler-cli (if memory serves), ng update --all should take care of that, giving you the latest angular/cli version in the process (assuming you have a recent cli version installed globally).
package.json
ng update --all
angular 6+
angular/cli 7+
yarn add/npm install the following
chokidar
npm-run-all
(runs our tasks in parallel with the -p flag. -p kills all processes, -l gives each running task a specific color and name in the console)
ts-node (runs nodejs in it's ts-format)
nodemon // for restarting ts-node
add something similar to my util/await-file.js (after some consideration I added my own file-watcher code below even though it wasn't exactly written with the intentions to be put up on display...)
modify your package.json scripts like below
modify your angular.json to match your folder names, following my examples, mainly the "server"'s outputPath should be changed from dist/server to dist/ng-server.
package.json scripts
"dev": "npm-run-all -p -r -l watch:ng-server watch:browser watch:node",
"watch:browser": "ng build --prod --progress --watch --delete-output-path",
"watch:ng-server": "ng run ng-universal-demo:server --watch --delete-output-path",
"watch:node": "yarn run watch:file-exist && yarn run ts-node",
"ts-node": "nodemon --exec ts-node server.ts -e ts,js",
"watch:file-exist": "node utils/await-file.js",
util/await-file.js
const chokidar = require('chokidar');
const fs = require('fs');
const path = require('path');
const DIR_NAME = 'ng-server';
const DIST_PATH = './dist';
// creates dist folder if it doesn't exist - prior to adding it to the watcher.
if (!fs.existsSync(DIST_PATH)) {
fs.mkdirSync(DIST_PATH);
}
const watcher = chokidar.watch('file, dir', {
ignored: '*.map',
persistent: true,
awaitWriteFinish: {
stabilityThreshold: 5000,
pollInterval: 100
}
});
const FOLDER_PATH = path.join(process.cwd(), 'dist');
watcher.add(FOLDER_PATH);
console.log(`file-watcher running, waiting for ${DIST_PATH}/${DIR_NAME}`);
function fileFound() {
console.log(`${DIR_NAME} folder found - closing`);
watcher.close();
process.exit();
}
watcher
.on('add', function (filePath) {
const matchWith = path.join('dist', DIR_NAME);
const paths = filePath.split(path.sep);
const fileName = paths[paths.length - 1];
if ((filePath.indexOf(matchWith) >= 0)
&& fileName.indexOf('.js') > fileName.length - 4) {
fileFound();
}
})
.on('error', error => console.log(`Watcher error: ${error}`));

"npm run start" and using "http://localhost:4200" works for me. Even with Angular 10

Related

process.env.NODE_ENV suddenly UNDEFINED in current SvelteKit project

Inside svelte.config.js I was using this
const dev = process.env.NODE_ENV === 'development';
to conditionally set a base path which was working fine in projects with #sveltejs/kit#1.0.0-next.350 and *.357
After installing now the most recent SvelteKit version #sveltejs/kit#1.0.0-next.386 it only results to undefined
Differences I notice is that the new project lists "vite": "^3.0.0" as devDependency and the script changed from "dev": "svelte-kit dev", to "dev": "vite dev"
Update: It's also the case for a project with #sveltejs/kit#1.0.0-next.366, vite#2.9.14, "dev": "vite dev" - so the switch was before vite 3.0
Going through the vite docs I find import.meta.env, but that's also undefined inside svelte.config.js
Switching from Node v16 to 17 didn't make a difference as well
What changed and how can I now distinguish between dev and build mode?
The behavior you describe was introduced in 100-next384
[breaking] remove mode, prod and server from $app/env (#5602)
and here is the relevant discussion
respect --mode, and remove server, prod and mode from $app/env
I think you should use Vite capabilities to configure dev VS production/build modes.
Update
Considering better your case, a way to solve the issue is to set a value for the NODE_DEV environment variable, like (Linux/Mac):
export NODE_ENV=development && npm run dev
There are other ways to do this but at least for development it should do the trick.
This might help someone in the future. I encountered this error when I created an express server in a react application. I created the server directory in the root folder of the react application and I was running both react app and express server at the same time.

How to add angular 4 to existing node.js application

I have a node.js application set up to use typescript.
The application is supposed to be deployed on heroku.
The node.js application is set up as an restful api for things like auth, registration and requests.
I would like to know what dependencies I need to add in order to begin building an angular 4 application in the same project.
I saw an issue on github where the recommendation was to use ng init however that is no longer an option. ng new creates an entirely new project directory rather than adding the dependencies and files.
There is another question on here where the OP marked his own answer as correct which basically says "use meteor".
EDIT:
I understand how to serve an angular 2+ application along side from within a node.js app when working locally, just build and serve the index.ts file. But how can I have the angular development files coexist with node.js files in git so I can compile them and deploy them together?
I had the same case, I had a parse server on heroku and wanted to group it with Angular.
In my server.js file :
app.use(express.static(__dirname + '/dist'));
(You just need express)
I also use internationalization, so I made something quick (early stage, please don't judge) :
app.get('/', function(req, res) {
let userLanguage = req.headers["accept-language"];
let langs = ['fr', 'en'];
let preferred = userLanguage.substr(0, 2).toLowerCase();
console.log('User\'s preferred language is ' + preferred.toUpperCase());
if (langs.indexOf(preferred) >= 0) { res.redirect(preferred); } else { res.redirect('/en'); }
});
My NG commands :
"postinstall": "npm run build-i18n",
"i18n": "ng xi18n --output-path src/i18n --out-file messages.xlf",
"build-i18n:fr": "ng build --output-path=dist/fr --aot --prod --bh /fr/ --i18n-file=src/i18n/messages.fr.xlf --i18n-format=xlf --locale=fr",
"build-i18n:en": "ng build --output-path=dist/en --aot --prod --bh /en/ --i18n-file=src/i18n/messages.en.xlf --i18n-format=xlf --locale=en",
"build-i18n": "npm run build-i18n:en && npm run build-i18n:fr"
My apps is built in 2 folders for the actual 2 languages, and the user is redirected to either of them when he comes to the app.

Run node server and webpack together using package.json

I have completed todo app by learning from this video:
Super MEAN Stack Tutorial: Angular, Node/Express, Webpack, MongoDB, SASS, Babel/ES6, Bootstrap
In that video at time 19:18 at this url it is taught that I should use the below two commands in seperate git-bash instances if I want to run it in windows using npm run dev:
node server
webpack-dev-server --progress --colors
But in Linux (or any other OS than windows) you can use this script:
"Scripts": {
"start": "NODE_PATH=$NODE_PATH:./src node server",
"dev": "npm start & webpack-dev-server --progress --colors"
}
So, Is there any way I can do the same in windows?
Also, In that tutorial I can see that port no. 3000 is assigned to node server, but due to using dev dependencies he runs the localhost:8080 in browser. You can see that here. After the tutorial finishes, I followed along and created that app. Now I would like to deploy it. So, I would first like to learn to run test my site in non-dev dependencies mode. i.e. when I type localhost:3000 in browser, my app should run successfully. So, can anybody explain the steps for that?
Update:
I am a newbie in node.js. I watched many videos on node and tried to learn something from that. In all the videos I see that I run node server on port no. 3000 and then I type localhost:3000 in my browser. Now lastly I watched video about mean stack in which he uses webpack. Now, I am confused. I think there are two servers running. first server is webpack's server and second server is node's server. Upto today I typed localhost:3000 in my browser because I mentioned that port 3000 will be used by node in my code. But now in the video he is running localhost:8080 in browser. It means webpack's server is used. Then what happened to node server. Why can't I just run localhost:3000? Also in the video it is explained that webpack is a dev dependency. So, I think after the app is completed and ready to be deployed, my project can be run on the node server (by making some changes to the code, I am not sure). Let's take an example. Now I don't want to deploy the app to a real server. I want the same app to run on my friend's pc. He is not a developer. So, he should not depend on webpack as webpack is a dev dependency. So, he should be able to run the app on node server instead of webpack's server. So, he should type localhost:3000 instead of localhost:8080. That's what I don't understand.
Let's break this down:
If you've defined this script:
"Scripts": {
"start": "NODE_PATH=$NODE_PATH:./src node server",
"dev": "npm start & webpack-dev-server --progress --colors"
}
... then this npm command: npm run dev
... actually invokes these two actions:
a) npm start & # Runs NPM in the background
b) webpack-dev-server --progress --colors # Concurrently runs webpack in the foreground
You can accomplish the same thing in many ways using Windows, starting with a simple .bat file like this:
EXAMPLE: RunDev.bat:
start npm start
webpack-dev-server --progress --colors
=======================================================================
STRONG SUGGESTION:
Please forget about watching videos for a few moments. Try a couple of "hello world" tutorials. More importantly, play with the actual code. Try changing things in the code, and see what happens.
Forget about webpack, at least for the moment.
Think of npm as a "build tool"; not as a way to run your application. At least for a moment.
Focus on "node". Write a "node application".
Part of your "node application" will require "ExpressJS" and "Jade" (now renamed "pug" - I'm still using "Jade"). Use npm to get your ExpressJS and Jade dependencies, but stay focussed on Node.
SUGGESTED TUTORIAL:
A Simple Website in Node.js, Ben Gourley
Be sure to:
a. Download the code
b. Work through the tutorial, using the downloaded code
Please post back (a new post) with any specific questions you might have as you work through the tutorial.

Deploy the backend and frontend on the same Heroku app/dyno

At the root of my project, I have a frontend and backend folder. Both folders contain a package.json that list their dependencies. How do I tell Heroku to run npm install on both folders when deploying the application? It seems like Heroku expects to have a single package.json file by default. Do I have to do something with a Procfile? The Heroku documentation doesn't seem to tell much about my specific question.
Thanks for the help!
I just successfully completed this goal using static files created during a heroku postbuild step, as described in this blogpost. I have a React frontend (could be anything though) and Express API backend. Each process has its own port in dev, but deploying on Heroku uses just one total.
Put the working frontend in a subdirectory of root (such as /frontend).
Put the working backend in a subdirectory of root (such as /api -- the blogpost assumes the backend remains in the root directory -- either way is fine).
Proxy API requests from the frontend to the backend by adding this line to /frontend/package.json (replacing 5000 with your backend port):
"proxy": "http://localhost:5000",
Add the following to api/app.js (or api/index.js) in the backend (be sure the last part is AFTER you define the appropriate backend [or api] paths):
const path = require('path')
// Serve static files from the React frontend app
app.use(express.static(path.join(__dirname, '../frontend/build')))
// AFTER defining routes: Anything that doesn't match what's above, send back index.html; (the beginning slash ('/') in the string is important!)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/../frontend/build/index.html'))
})
Edit the root directory's /package.json file with something like the following (note that using the concurrently package allows an easy way to run the whole app locally with npm run dev, but only heroku-postbuild is required here):
"scripts": {
"frontend": "cd frontend && npm start",
"api": "cd api && nodemon app.js",
"dev": "concurrently --kill-others-on-fail \"npm run api\" \"npm run frontend\"",
"heroku-postbuild": "cd frontend && npm install && npm run build"
},
Make sure you install all backend package dependencies in the root directory, or you will get errors.
Make sure your /Procfile has something like web: node api/app.js
Seems that you can put a package.json file on the root of the project and use scripts to invoke npm i in both folder.
https://devcenter.heroku.com/articles/nodejs-support#customizing-the-build-process
Something like cd front && npm i && cd ../back && npm i
But i should say that if they are running on different ports, it may not work as it seems that only one web process per procfile is available.
this last point is to confirm.
You can define several entry points for your project in the Procfile :
web: cd front && npm i && npm start
server: cd backend && npm i && npm start
However, you have to upgrade to Hobby at least. It's 7$/dyno/month.

Auto reloading a Sails.js app on code changes?

Currently is seems that for any code change in a sails.js app you have to manually stop the sails server and run sails lift again before you can see the changes.
I was wondering if there is any way when running in development mode to automatically restart the sails server when it detects a code change?
You have to use a watcher like forever, nodemon, or something else...
Example
Install forever by running:
sudo npm install -g forever
Run it:
forever -w start app.js
To avoid infinite restart because Sails writes into .tmp folder, you can create a .foreverignore file into your project directory and put this content inside:
**/.tmp/**
**/views/**
**/assets/**
See the issue on GitHub:
Forever restarting because of /.tmp.
You can use sails-hook-autoreload
Just lift your app as normal, and when you add / change / remove a model or controller file, all controllers and models will be reloaded without having to lower / relift the app.
For example with nodemon to watch api and config directories
.nodemonignore contents
views/*
.tmp/*
.git/*
Run the command after creating .nodemonignore
$> nodemon -w api -w config
Example for supervisor to ignore 3 directories
$> supervisor -i .tmp,.git,views app.js
If you're using Sails 0.11, you can install this hook to automatically reload when you change models or controllers (views do not require reloading):
npm install sails-hook-autoreload
https://www.npmjs.com/package/sails-hook-autoreload
install nodemon globally or locally.
npm install nodemon --save
npm install nodemon -g
install sails locally in you project as follows
npm install sails --save
then change package.json
from
"scripts": {
"debug": "node debug app.js",
"start": "node app.js"
},
to
"scripts": {
"debug": "node debug app.js",
"start": "node app.js",
"dev": "export NODE_ENV=development && nodemon --ignore 'tmp/*' app.js && exit 0"
},
then
npm run dev
I had the same problem and I have solved it using grunt-watch and grunt-forever with sails#beta tasks. The result is 4 grunt commands:
UPDATE: tasks are available in the current sails version (it's no longer beta :>)
start Starts the server
stop Stops the server
restart Restarts the server
startWatch Starts the server and waits for changes to restart it (using grunt-watch). This is probably your solution, but the other commands are also useful.
Here's the code - I'm using sails#beta, which includes a tasks directory, I don't know if this is included in previous versions:
First of all you have to install forever in your sails directory:
npm install grunt-forever --save-dev
tasks/config/forever.js Configure forever task.
module.exports = function(grunt) {
grunt.config.set('forever', {
server: {
options: {
index: 'app.js',
logDir: 'logs'
}
}
});
grunt.loadNpmTasks('grunt-forever');
};
tasks/config/watch.js (edit) Edit watch task in order to add a new rule
// api and assets default rules
,
server: {
// Server files to watch:
files: [
'api/**/*',
'config/**/*'
],
// Restart server
tasks: ['forever:server:restart']
}
tasks/register/watchForever.js Register your custom tasks (this file can be renamed to whatever you want)
module.exports = function(grunt) {
// Starts server
grunt.registerTask('start', [
'compileAssets',
'linkAssetsBuild',
'clean:build',
'copy:build',
'forever:server:start'
]);
// Restarts the server (if necessary) and waits for changes
grunt.registerTask('startWatch', [
'restart',
'watch:server'
]);
// Restarts server
grunt.registerTask('restart', [
'forever:server:restart'
]);
// Stops server
grunt.registerTask('stop', [
'forever:server:stop'
]);
};
With this you should be able to use
grunt startWatch
and make your server wait for changes to be restarted :>
Hope this helped!
Better you use
npm install -g nodemon
i am using this, and it will helps to improve my developing speed. no need to edit any files for this one!.
after installation
nodemon app.js
For anyone coming to this question now, it seems that this is no longer necessary - an application launched with sails lift will have a grunt watch task running, and code changes will be visible without a restart.
I didn't realise this was happening at first because there's nothing to indicate what's happening in the console, but it does seem to work without a restart (I'm using Sails 0.11)

Resources