Frontend evolution

Modern web applications

Damian Dulisz

Monterail/pwr

Projects in the past

HTML

CSS

JavaScript

50%

30%

20%

Source lines of code/time spent in general*

 

* from my experience

HTML

CSS

JavaScript

15%

15%

70%

Now

Sometimes

HTML

1%

JavaScript

99%

So... more jQuery?

Not rly

Why such a drastic change?

JavaScript development now:

The language got much better.
 

The platform improved and follows standards, meaning jQuery is no longer needed.
 

The ecosystem has grown so big, it can’t be ignored.
 

JavaScript succeeded where Java failed – it is now run on almost every possible platform.

ES6 and beyond

JavaScript implements the ECMAscript standard (currently ES 2016).

Each version extends the language with new syntax and features.

Sadly, not all browsers support the whole standard.

Thankfully we got Babel :) 

Transpilers like Babel, translate ES6+ code into plain old ES5 so usually, you don’t have to worry about compatibility.

You can even use experimental proposals to the language, although that’s not recommended!

And there is TypeScript, a superset of JavaScript with static type checking and more.

So what’s new?

arrow functions
destructuring
spread operator
rest parameter
promises
async/await
generators
block scoped variables
classes
decorators
and more...
type checking
interfaces
es6 modules

Some examples

// arrow functions
const Sum = x => y => x + y
const Add5 = Sum(5)
Add5(10) // 15
// spread
const x = { a: 1, b: 2 }
const y = { b: 5, c: 8 }
const z = { ...x, ...y, d: 10 } 
// { a: 1, b: 5, c: 8, d: 10 }
// promises
function getUsers () {
axios.get('/api/v1/users').then(response => { this.data = response })
}
// or async/await
async function getUsers () {
this.data = await axios.get('/api/v1/users')
}
// destructuring, rest
const validatorString = 'between:5:15'
const [validator, ...args] = valdiatorString.split(':')
console.log(validator) // 'between'
console.log(args) // [5, 15]

ES2015 Modules

import { fetchUser as getUser } from './userService.js'
import * as MUTATIONS from './mutation-types.js'
import UserTable from '~components/UserTable.vue'
// userService.js
export function fetchUser () { ... }

// mutation-types.js
export const SET_USERS = 'SET_USERS'
export const DELETE_USER = 'DELETE_USER'

// UserTable.vue
export default { ... }

To make use of those modules

we need a bundler

webpack

webpack

  • Can statically analyse your bundle and tree-shake it, leaving only the used code in the final bundle.
     
  • Can automatically split your bundle into multiple asynchronously loaded chunks improving the load time and performance (for example based on router views)
     
  • Can take care of things like cache busting, transpilers, preprocessors, inlining images​
     
  • Hot-module replacement and much more!

There are others

Browserify

Rollup.js

Shines for bundling libraries

This brings us to the rise of Single Page Applications

Single Page Application (SPA)

Usually:

  • Consist of just an index.html file and a bunch of JavaScript and CSS files.

  • Completely decoupled from backend

    • Server is no longer responsible for generating HTML files.

    • Thus HTML is no longer the source of data. JavaScript is.

  • JavaScript controls everything including the routing.

  • JavaScript can asynchronously fetch the data from different sources.

  • Better user experience (no page reloads, feels faster)

How is it built?

Mostly components!

Used to create reusable blocks of functionality to use across the application.

Dumb, Presentational

Have no idea about the context they are used in. Reusable.

Configurable with props.

Examples:

  • DatePicker
  • DataTable
  • Multiselect

Smart, containers

Used to implement app specific features. Rather not reusable.

Examples:

  • UserView
  • NewUserForm
  • Dashboard

Components

Are usually divided into two groups based on what information they contain.

Functional and/or reactive programming

  • Thinking about the data model rather than the view.
  • Declarative views.
  • Imperative changes to the DOM are considered an anti-pattern.
  • JavaScript no longer enhances the app. It is the app.
  • VirtualDOM

So what’s this VirtualDOM thing?

Since a HTML document is basically a tree composed of DOM nodes, it can be represented as an JavaScript object.

If it can be an object, it can be created with a function.

 We can compare the virtualDOM objects to find out which DOM node needs to be created, updated or removed.

Once the data changes, we calculate the new virtualDOM object, diff it with the old one and patch the changes.

3. VirtualDOM

// Example virtualDOM object
const node = { type: '...', props: { ... }, children: [ ... ] }

// Common helper function
function h (type, props, children) {
  return { type, props, children }
}

// example usage
const render = (
  h('div', { class: 'my-form' }, [
    h('label', {}, 'This is a label'),
    h('input', { type: 'text' }),
    h(‘button’, { type: ‘button’ }, 'Save!')
  ])
)

// or when using JSX
const render = (
  <div className="my-form">
    <label>This is a label</label>
    <input type="text"/>
    <button type="button">Save!</button>
  </div>
)

3. VirtualDOM

// both will return
const render = { 
  type: 'div', 
  props: { class: 'my-form' }, 
  children: [
    { type: 'label', props: {}, children: ['This is a label'] },
    { type: 'input', props: { type: 'text'}, children: [] },
    { type: 'button', props: { type: 'button' }, children: ['Save!'] }
  ] 
}

Imagine DOM = f(state) where state is the data model. That’s how it works.

 

Imperative changes to the real DOM are considered an anti-pattern and will be ignored after the next update.

This is basically how modern front-end libraries and frameworks work

Selected front-end frameworks

Angular

React

Vue

Ember

Just a library

Less opinionated

Very flexible

Full framework

Very opinionated

Not really flexible

Just a library

Less opinionated

Very flexible

My framework of choice

Vue.js

The Progressive Framework

  • Easy to learn and master
  • Very flexible with super performance
  • Not opinionated
  • Great developer experience
  • Some interesting concepts like single-file components (.vue)
  • Reactive "engine" included
  • High quality supporting libraries from the core team
  • Less boilerplate, more productivity
  • Takes the best from React and Angular

Vue

  • Can be added with a <script> tag instead of jQuery
  • Or used with a more sophisticated setup unleashing it full potential
  • Makes complex things simple
  • Works great with code splitting
  • TypeScript support

Beyond the browser

Bonus slides

So we know that webpack is bundling our front-end files.

Apart from tooling, Node.js can also be used for server-side applications just like Ruby, Java or PHP.

But webpack is also mostly written in JavaScript that runs on Node.js, which is basically the V8 JavaScript engine from Chromium running in the background of your system.

Why would you want to use JavaScript as a server language?

  • It’s crazy fast! Since the VM is written in C++ it can be many times faster than Ruby, PHP or even Python.
     
  • Has a non-blocking nature (the event loop) making it great at handling hundreds of concurrent connections.
     
  • You can share the same code (and libraries) between the client and the server.

Why would you want to use JavaScript as a server language?

You can even render front-end apps (Vue, React) on the server so that the user receives a meaningful first paint (HTML full of relevant data) before the SPA client takes over.
 

Great user experience and SEO support.
 

Such apps are often called isomorphic applications.

Btw. do you know those apps?

Do you know what they all have in common?

Electron

It lets you write multi-platform native-like apps that run inside a Chromium-based window with access to the filesystem and native OS API.

 

Works offline. Uses HTML, CSS and JS. Frameworks included.

 

Most of the code can be shared between the web app and the electron app.

 

Runs a Node.js process in the background, but can also make use of .NET (C#) code.

Electron

What if we could use it not only for creating HTML DOM nodes but nodes in general?

Remember VirtualDOM?

Does that ring a bell?

<view>
  <text>
    Hello World!
  </text>
</view>

Turns out we can.

Ever used Instagram or AirBnB on you phone?

Thanks to the abstraction layer of the virtual DOM we’re not limited to just the web.

React native

Runs on the internal JavaScript engine of Android and iOS (not a webview)

 

Can make use of native UI elements as well as the platform API

Progressive Web Apps

What does progressive mean?

It means it’s like a regular web app, just progressively enhanced.

Progressive Web Apps

Possible enhancements:

Offline mode (with background sync once back online)

Push notifications

Able to add to Home Screen (Android only)

Try it out, go to mobile.twitter.com

The end

 

Thank you!

Questions?

Ewolucja Frontendu

By Damian Dulisz

Ewolucja Frontendu

  • 1,731