Frontend

Frontend

Rendering is the process of gathering data (if any) and load the associated templates (or just send the output directly). Then apply the gathered data to the associated templates. The final output is sent to the user.

 This concept is quite the same for both client and server.


You can have pure client-side apps which do all rendering and logic with Javascript, and which only reach out to the backend for API operations.

You can also have pure server-side apps (most common with PHP, I’d say) where all the HTML and content is pre-rendered on the server before being downloaded by the web browser.

Client-side rendering and server-side rendering are commonly mixed, though. For example, stackoverflow.com renders the web page with the questions and answers on it on the server-side and sends it to you. Client-side rendering is then used for the upvote/downvote AJAX, adding new comments, and for previewing answers to questions in the browser.

“My understanding of these kinds of apps is that everything is bundled together (except binary assets, like images and fonts) and served as one big monolith. The server you are running usually builds (with webpack) that all for you and serves it as such. In a traditional, static website, all the assets are kept separate (your server might be doing this when running in “development mode”)… Look at the source that is being served, that would immediately show you if it’s requesting separated assets. Render Step


Three types of Rendering Pages on a browser:

Server Side: Pre-rendered or Statically-Generated

Static HTML, CSS: Static, rendered HTML response.

Although it may be confused with SSR, but the idea is a bit different. With this method during a building phase  html files are generated which will be served from the server. Such html files can be effective at rendering hundreds of components which will take time if done on client-side.The application can be pre-rendered once in a specific state, only to send it to the end user in simple html files in the fastest way possible while using http hosting. If you’re hosting your build with a static hosting provider you can use react-snapshot or react-snap to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. The primary benefit of pre-rendering is that you get the core content of each page with the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines

If you’re only investigating SSR to improve the SEO of a handful of marketing pages (e.g. /, /about, /contact, etc), then you probably want prerendering instead. Rather than using a web server to compile HTML on-the-fly, prerendering simply generates static HTML files for specific routes at build time. The advantage is setting up prerendering is much simpler and allows you to keep your frontend as a fully static site.

Static rendering = fast responses. has the advantage of being able to serve requests stupidly fast, because nothing needs to be generated on the fly. In fact, since your site’s responses are all generated ahead of time, you can store the files all over the world on a CDN (on the edge). This gives your site ridiculously fast response times. Server rendering is always slower than serving static content. However, you’d need to mess things up pretty badly for the slowdown to be anything greater than a second — and whether this kind of delay matters really depends on your business requirements.

can’t predict requests e.g. Search Engine or response changes on every request with time or with who is viewing it (auth)? No Static Rendering. With static rendering, you need to generate responses for every possible request ahead of time. For websites focussed on high quality content, this is fine — static renderers like Navi can generate hundreds of pages in mere seconds. But what if you’re building something where you can’t predict all possible requests, like a search engine? Or what if you have a lot of user generated contend, and the response changes on every request? In that case, you’ll need server rendering. Of course, for what server rendering lacks in speed, it makes up for in flexibility. It allows you to:

Example: Jekyll blog


Server side: Rendered on-the-fly

Dynamically rendered HTML. Template + dynamic data. A browser makes a request to a server, the server runs application pre-rendering and responds with a generated html and JS code for any interactivity (which can ask for more requests to be sent in the backend, make elements visible based on interaction etc.). On the browser site the JS logic is automatically attached to the rendered state and the application can used as usual.


This approach allows the user to receive everything at once and also caters to browsers that don’t have good JavaScript support, but it also means everything takes a bit longer before the browser gets the first <html> tag.

Pros:

Example: A typical PHP or WordPress site, the page is loaded from content that is coming via HTTP which was rendered on the server and comes as fully rendered HTML.

Examples of traditional SSR languages/frameworks are PHP, Java, ASP .NET and Node.js.

Example: request routes to node server. The node server picks the template based on route, looks up data in database. And send the response (template with the data attached). Example: Jade/Pug with Express, Django

SSR

Example: Stack Overflow renders questions


Client-side: Single Page Applications

HTML template with with JS: it is rendered with the help of JS.

This approach allows you to render your structure quickly on the server-side, then let the user’s JavaScript pick up the actual content. Pros:

A single-page application (SPA) interacts with the user by dynamically rewriting the current web page with new data from the web server, instead of the default method of the browser loading entire new pages. The goal is faster transitions that make the website feel more like a native app. Such applications generate whole content in the browser runtime.

Typically the client-side applications receive from the server a basic html structure with an empty placeholder “div” where all application components will be rendered. All necessary HTML, JavaScript, and CSS code is either retrieved by the browser with a single page load, or the appropriate resources are dynamically loaded and added to the page as necessary, usually in response to user actions. (A React app built with CRA sends a .js file to the client and the clients’ browser JavaScript engine creates the markup after the .js file is loaded.
 the built .js file (Files like these: static/css/app.3136db4aece9d70bd7458ade08e813c8.css, static/js/app.5a5b57a7c4b45cfcb1d8.js’) is first downloaded to the user’s browser before the rest of the page starts loading. This increases the initial load time and some web crawlers are unable to index the site.)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1>
    <title>Title</title>
</head>

<body>
    <div id="root"></div>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <script src="../dist/bundle.js"></script>
</body>

</html>

The page does not reload at any point in the process, nor does it transfer control to another page, although the location hash or the HTML5 History API can be used to provide the perception and navigability of separate logical pages in the application. Once this code has arrived, JS starts making request to the backend for data (in the form of JSON responses).

Optional: You might want to modify the tag or environmental variables before it gets sent to the browser by your production server. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime. The SPAs usually have provision to add a bit of rendering-on-the-fly or pre-rendering [here](https://create-react-app.dev/docs/title-and-meta-tags/#generating-dynamic-meta-tags-on-the-server).


How does the browser turn code into graphics?

But we do not merely want a static painting, we want something we can interact with. We want events to happen when we click buttons. We want popup windows and animations (example: transitions from Like-> Unlike which happen when we click on “Like” button on Facebook).

Reference


What does the “build” step do?

But for any nontrivial project, you’ll have a number of build steps: pre-compilation (template engines -> html or template strings -> js render functions), transpiling (typescript, coffeescript, new js, jsx -> old js) , minifiying, organizing your outputs for distribution, determining what needs to be updated, optimizing images, etc. This is where build tools come in. Webpack, JSPM, and Browserify take care of transpilation alongside all of the other magic they work (bundling, module loading, minifying etc.).


Example: Babel

Babel: Transpiles JSX to valid javascript. Without using node package and preprocessing, the script tag is a great way to try React but it’s not suitable for production. It slowly compiles JSX with Babel in the browser and uses a large development build of React.
 npm install –save-dev @babel/core@7.1.0 @babel/cli@7.1.0 @babel/preset-env@7.1.0 @babel/preset-react@7.0.0. babel-core is the main babel package — We need this for babel to do any transformations on our code. babel-cli allows you to compile files from the command line. preset-react and preset-env are both presets that transform specific flavors of code — in this case, the env preset allows us to transform ES6+ into more traditional javascript and the react preset does the same, but with JSX instead.

Bundling your application removes anything that isn’t essential. This includes:

Webpack bundles all the modules and delivers it to the browser as one file, so that they can be applied by the browser (e.g. when reactDOM mounts). When your code is bundled, you just have to copy the files into your web server. Then configure your web server to serve files stored at that location.

When a React application is “compiled”, it basically traverses the graph of dependencies and lumps them all together. It then may do additional things such as “minifying” the source, which makes it smaller – for faster downloads – but obfuscates it to the point of making debugging basically impossible. When it is generated server-side, you get it (almost) as it was originally written, perhaps even instrumented with debugging tools (e.g., I know Vue does this, for example; I’d imagine React does the same) to make it much easier to follow. For example, it might do hot-code reloading as you make changes to the source.

Bundler/linker (Webpack, Browserify): For a number of good technical reasons CommonJS modules (i.e. everything in npm) cannot be used natively in the browser. You need a JavaScript “bundler” to “bundle” these modules into .js files that you can include in your web page with a 

When executed in the browser, webpack needs to know where you’ll host the generated bundle. Thus it is able to request additional chunks (when using code splitting) or referenced files loaded via the file-loader or url-loader respectively. For example: If you configure your http server to host the generated bundle under /assets/ you should write: publicPath: “/assets/”

the publicPath is just used for dev purpose, I was confused at first time I saw this config property, but it makes sense now that I’ve used webpack for a while suppose you put all your js source file under src folder, and you config your webpack to build the source file to dist folder with output.path. But you want to serve your static assets under a more meaningful location like webroot/public/assets, this time you can use out.publicPath=’/webroot/public/assets’, so that in your html, you can reference your js with . when you request webroot/public/assets/bundle.js the webpack-dev-server will find the js under the dist folder

Update: original: the publicPath is just used for dev purpose, this is not just for dev purpose No, this option is useful in the dev server, but its intention is for asynchronously loading script bundles in production. Say you have a very large single page application (for example Facebook). Facebook wouldn’t want to serve all of its javascript every time you load the homepage, so it serves only whats needed on the homepage. Then, when you go to your profile, it loads some more javascript for that page with ajax. This option tells it where on your server to load that bundle from

Tip: Minify JavaScript for Production Before deploying your website to production, be mindful that unminified JavaScript can significantly slow down the page for your users.

If you already minify the application scripts, your site will be production-ready if you ensure that the deployed HTML loads the versions of React ending in production.min.js:

If you don’t have a minification step for your scripts, here’s one way to set it up.


Rendering

pre-compilation The associated build setups automatically performs pre-compilation of templates for you, so the built code contains the already compiled render functions instead of raw template strings. The easiest way to pre-compile templates is using Single-File Components.

<template>
  <div>
    <h1></h1>
    <h3></h3>
    <p>Current state of the counter is: </p>
    <button @click="increaseCounter">Increase Counter!</button>
  </div>
</template>
<script>
  export default {
    data: function(){
      title: "Hello Everybody",
      subtitle: "Just an example",
      counter: 0
    },
    methods: {
      increaseCounter() {
        this.counter++;
        console.log('Counter increased!');
      }
    }
  }
</script>
<style scoped>
  h1 {
    color: red;
    text-decoration: underline;
  }
  h3 {
    font-weight: 900;
  }

Use pre-compilation features by separating your JavaScript and CSS into separate files:

<!-- my-component.vue -->
<template>
  <div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>
<style src="./my-component.css"></style>
<div>
    <header>
        <h1>I'm a template!</h1>
    </header>
    <p v-if="message"></p>
    <p v-else>No message.</p>
</div>

render:

function anonymous(
) {
  with(this){return _c('div',[_m(0),(message)?_c('p',[_v(_s(message))]):_c('p',[_v("No message.")])])}
}
staticRenderFns:
_m(0): function anonymous(
) {
  with(this){return _c('header',[_c('h1',[_v("I'm a template!")])])}
}

https://stackoverflow.com/questions/40839395/correctly-configure-webpack-dev-middleware-with-vuejs-project

During development with yarn serve/vue-cli-service serve webpack’s dev-server handles (hot) bundling of the code on every code change and serves each hot build immediately to your browser request.  

HTML Webpack Plugin: auto inject references to the build files into your HTML file in the bundling process. Example: We’re building a multi-tenant app, so we’re creating an index.html for each tenant (and later in our build pipeline rename for example /dist/templates/UAT-AWS/index.TenantName.html –> /dist/index.html

would like to use the webpack-dev(and hot)-middleware to serve my index.html and create a bundle in memory from my src folder. To serve the index.html file you need to have a dev server running. It sounds like you are successfully doing this based on your logging of the creation of your bundle in memory. However I can’t see a file for it in your set up? I’ve assumed another file below called: dev-server.js and it would be your entry point to serving your app, i.e. npm run dev: In webpack this dev server is generally going to be express and it’s the config that you pass to your express server that will serve your index.html. As you are wanting hot-reloading you will pass express your webpack config through your middleware layers. For hot reloading you’ll need two main middlewares:


Vue: One important thing to note is that separation of concerns is not equal to separation of file types.  In modern UI development, we have found that instead of dividing the codebase into three huge layers that interweave with one another (HTML, CSS and JS), it makes much more sense to divide them into loosely-coupled components and compose them. Inside a component, its template, logic and styles are inherently coupled, and collocating them actually makes the component more cohesive and maintainable.

  1. Source code is not a good representation of what it looks like to a web browser; a page load (which is the rendered version) is a better representation. Search engine crawlers earlier used to look at pre-rendered html, now they look at fully rendered. 

19 November 2020