Hot reloading in visual studio 2017 for asp.net core spa (react) app with custom web server used via proxy - node.js

I have a asp.net core 2.2 react template based app
The react app under ClientApp has my own build script for react app which compiles stuff in a lib folder under ClientApp via 'npm run build' custom script.
More importantly, the app runs with a custom node/express based web server (npm run start in clientapp would launch a web server script which would listen on say port 6000)
I cannot use the standard react development server that comes with template.
The startup.cs file of asp.net core layer uses it via spa.UseProxyToSpaDevelopmentServer (http://localhost:6000)
app.UseSpa (spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment ())
{
string reactDevServerUri = Configuration["ReactDevServerUri"];
spa.UseProxyToSpaDevelopmentServer(reactDevServerUri);
}
});
During debug session in vs 2017, on any change in typescript files in ClientApp\src folder, i need to
1.Invoke script 'build' in ClientApp\package.json to compile react app in ClientApp\lib folder
2. Restart my web server running via script 'start' to pick new changes in lib
3.Reload browser
Currently i have added a 'debug' script which uses nodemon to track changes in react app and restart server after build script
"debug": "nodemon -e ts,tsx --watch src --exec \"npm run build && npm run start\""
I still have to reload browser myself and it keeps failing until build/start are finished. I need a better way to do this in one go by proper configuration of encapsulating asp.net core project.
Please help me figure out a way :)

Related

Deploy React JS frontend from Node JS backend with MS Azure

I have deployed my backend express server to feed data to my React frontend app using Heroku. I used the following script to launch my frontend with heroku
"heroku-postbuild": "cd client && npm install && npm run build"
How can I do the same with MS Azure or Firebase? What type of server/hosting can handle this? I am brand new to full stack development so anything helps.
Similar question: How to connect and deploy React app with Node js backend?
file setup
scripts

React *create app* won't render when I go to localhost

I have spun up a React app using create-react-app and have my index.js file as below.
import React{ReactDOM} from "react";
import App from "/componects/App.js";
ReactDOM.render(
<App/>,
document.getElementById('root')
);
My server.js file is as
const express = require('express');
const app = express();
app.get("/", function(req,res){
res.sendFile("fullpath/index.js")
});
app.listen(3000, function(){
console.log("app listening on port 3000");
})
I have checked my root route and it works when I don't send the full path. I do specify the full path in the code, but I want to keep it private for this post.
I do have a jsconfig file. When I go to localhost I receive all as plain text of the file. I only get the code itself. How can I fix this?
Quickly answer
You are totally wrong and you are confusing technologies: Node.js and React.
Usually you cannot mix these technologies.
As a summary, Node.js does not understand React code, that is why the following line in your code is unexpected, crazy and will fail:
res.sendFile("fullpath/index.js")
res.sendFile is for Node.js server-side rendering (SSR)
index.js is React code
If your create-react-app workspace is correct and standard, execute this line to start your react code in developer mode:
npm run start
If your react code is fine, the classic http://localhost:3000 will open on your local browser.
Long answer
Concepts
Server-side rendering (SSR) — the traditional rendering method, basically all of your page’s resources are housed on the server. Then, when the page is requested (commonly from web browsers), the HTML, JavaScript and CSS are downloaded. Also frameworks can dynamically can create the HTML-based on back end logic and finally download it. At this point, a lot of frameworks offer wonders for creating apps in no time with "amazing" functionalities.
Technologies: Java, C#, Python, Node.js, etc.
Client-side rendering (CSR) — Which is sometimes called "Frontend rendering" is a more recent kind of rendering method, this relies on JavaScript code executed on the client side (browser) via a JavaScript framework. So, when page is requested, a minimal, little or empty index.html, CSS and JavaScript content were downloaded. Here JavaScript is responsible to send or receive data and update a minimal section of the page without an entire page refresh.. Finally when user clicks or triggers some event, JavaScript code will send or receive the data commonly to an API REST (JSON) using an async call (Ajax).
Technologies: React, Angular, Vue.js, Aurelia, jQuery, pure JavaScript, etc.
Node.js
Is used in SSR frameworks
React.js
Is a CSR framework
Webs developed with React are called SPAs (single-page applications)
How can a CSR web be served?
In the developer stage (laptop/pc) you just need to use some kind of hot reload server (usually Node.js) which translates React into pure JavaScript code and link it to your browser.
These kind of servers are provided or developed by framework creators (Angular, Vue.js, React, etc.). Usually, they are pre-configured in your package.json as: npm run dev or npm run start
In testing/production stage, you should not use the hot reload server. You should perform a build which translates react into a pure JavaScript code. Usually is the command npm run build and the result are new files on some folder in your workspace: index.html, bundle.js, main.css, etc.
These files are ready to published on any HTTP server from minimal to a complex servers:
Apache
nginx
haproxy
Tomcat
WildFly
IIS
free/paid web FTP services
any decent server on any technology capable to serve HTML content.
React in the developer stage
If you are using create-react-app in a correct and standard way, there is a start script in your package.json file ready to use:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
I advice you to change it from start to dev to make it more intuitive. Let’s empty the start script to be correctly configured for the next stage.
React in the testing/production stage: Basic
If your React code is ready to be tested or used by real users in the real world, and your create-react-app workspace is correct and standard, these are the required and minimal steps:
install a minimal Node.js HTTP server
npm install http-server --save
add this in your script main:
"start": "http-server ./build"
execute npm run build
if there is no errors and your static files are created (index.html, CSS, JavaScript, etc.), perform:
npm run start
For more information (custom port, etc.) check this minimal Node.js HTTP server implementation:
http-server: a simple static HTTP server
React in Testing/Production stage: Docker
If your package.json has correctly configured the standard scripts:
npm run build
npm run start (with http-server or another)
You could use Docker to deploy it on any Linux server in this universe:
FROM node:10
COPY . /opt/
WORKDIR /opt/
RUN npm install
RUN npm run build
ENV PORT 8080
EXPOSE 8080
ENTRYPOINT ["npm","run","start"]
Linux is the only option for real environments. Windows and Mac are just for the developer stage
React in the testing/production stage: Advanced server
What if your requirement needs:
user sessions
login/logout feature
user inactivity expiration
JWT OAuth 2 token refresh
any other feature that React or any CSR/SPA was not designed for
In this case you need an advanced server implemented in some technology like: Node.js, Java, Python, PHP, etc.
These implementations:
should expose your endpoints like: /login, /logout ready to be called from your React, Angular, or Vue.js
should handle the user session with any common way: memory, Redis, MongoDB, etc.
offer a login: basic authentication, Google, Microsoft, etc.
My first attempt was:
https://github.com/jrichardsz-software-architect-tools/geofrontend-server
I am planning a revamp with more features and unit tests.
React in the testing/production stage: Advanced API/microservices
All of the features explained in the previous paragraph could be implemented on any back end REST API or microservice.
With that, your CSR/SPA builds will still be static and won’t need any crazy HTTP server. Just the basics as explained at the start of this answer.
Express / Node.js is case-sensitive. You need to provide an absolute path to the file:
const app = require('express')();
app.get("/", function(req,res) {
// Absolute path
res.sendFile("C:/Users/%username%/fullpath/index.js")
});
app.listen(3000, function() {
console.log("App listerning on port 3000");
});
A relative path is when you are in a directory, and specify a file without specific location:
# Absolute path
C:/Users/John/path/to/file.txt
# Relative path
path/to/file.txt

How to setup and run ionic app and node express api within one application?

I have two separate applications one is the ionic app and other is node express api app. Is it possible to merge both in one application? Like for example when i enter npm run start it should run ionic serve and node index js both?
Typically after you finish developing your frontend you "build" it. This minifies and optimizes frontend files. For ionic: https://ionicframework.com/docs/cli/commands/build
This creates a folder(the default name can be "dist" or "build" etc). You put this folder in your backend folder, then serve it statically. For static serving check out https://expressjs.com/en/starter/static-files.html.
This way you deploy only backend, and it works. You can make api endpoint routes start with "/api" and "/" routes can be for frontend's static serving.
If you mean you want to do that for development purposes only, you can use concurrently command https://www.npmjs.com/package/concurrently
npm install -g concurrently
After installation, add this line to package.json script
"start": "concurrently \"command1 arg\" \"command2 arg\""
In command1: add ionic start command, like: ionic start
In command2: add node start command, like: nodemon server.js

Deploying an Angular App in Node JS (express) server through http-server

I'm trying to put an angular application in "production" on a local server that is generated by the http-server tool, but it does not return the of the index.html.
I followed these steps ...
ng build --prod (this throws me the project folder for production like this -> "dist / project-erp")
http-server
web server
Update:
So, I changed the base route to "/" but still happening in same situation :/
After many tests of building the project, the solution to launch it on the Express server (it worked for now) is to just do the command "ng build" instead of "ng build --prod", then the folders "dist / project-erp "put them on the backend server.

ServiceStack Hot Reloading Typescript

I'm using .net core and ServiceStack Angular SPA project template, and I want to enable hot reloading.
From what I saw on site here I only need to add:
Plugins.Add(new TemplatePagesFeature());
<i hidden>{{ '/js/hot-loader.js' | ifDebugIncludeScript }}</i>
And:
SetConfig(new HostConfig
{
DebugMode = true
});
And this works for HTML files, however, nothing happens when I modify TS files (in console or browser), do I need to configure something else in order to allow that?
EDIT
I thought that this will also start something like npm run dev (to run --aot) but does not look like that, so my temporary solution until I find more elegant way is to use something like this and shell extension:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.Shell("npm run dev");
}
The Development workflow for each template can be found on the project page for each template. E.g. the Angular SPA Project Template requires that you run either npm run dev or npm run serve which starts a watched client build:
Development workflow
Our recommendation during development is to run the dev npm script or Gulp task and leave it running in the background:
$ npm run dev
This initially generates a full development build of your Web App then stays running in the background to process files as they’re changed. This enables the normal dev workflow of running your ASP.NET Web App, saving changes locally which are then reloaded using ServiceStack’s built-in hot reloading. Alternatively hitting F5 will refresh the page and view the latest changes.
Each change updates the output dev resources so even if you stop the dev task your Web App remains in a working state that’s viewable when running the ASP.NET Web App.
Live reload with built-in Dev Server
The alternative dev workflow is to run the serve npm or gulp script to run Create React App's built-in Webpack dev server:
$ npm run serve
This launches the Webpack dev server listening at http://localhost:4200/ and configured to proxy all non-Webpack HTTP requests to the ASP.NET Web App where it handles all Server API requests. The benefit of viewing your App through the Webpack dev server is its built-in Live Reload feature where it will automatically reload the page as resources are updated.
Watched .NET Core builds
.NET Core projects can also benefit from Live Coding using dotnet watch which performs a “watched build” where it automatically stops, recompiles and restarts your .NET Core App when it detects source file changes. You can start a watched build from the command-line with:
$ dotnet watch run

Resources