Collective #542

Inspirational Website of the Week: Igor Mahr A web design full of lively motion with a truly unique feel. Our pick this week. Get inspired This content is sponsored via Syndicate Ads Easily Secure and Manage All Your Apple Devices in Minutes Jamf Now Read more

Collective #535

dreamt up by webguru in Uncategorized | Comments Off on Collective #535



Divi

Our Sponsor

Divi: The Powerful Visual Page Builder

Divi is a revolutionary WordPress theme and visual page builder for WordPress. With Divi, you can build your website visually. Add, arrange and design content and watch everything happen instantly right before your eyes.

Try it




C535_rooki

Rooki

Rooki is an online magazine for students, interns and juniors with intimate interviews, free design student awards and free resources.

Check it out






C535_zindex

Index fun

A very interesting analysis on which z-index values are used on websites. By Philippe Suter.

Read it






C535_multistep

Progress Tracker

An updated HTML component to illustrate the steps in a multi step process e.g. a multi step form, a timeline or a quiz.

Check it out






C535_fontmur

Free Font: Le Murmure

Recently expanded with Cyrillic, Le Murmure is a custom open-source typeface designed by Jérémy Landes for the design agency Murmure and released by Velvetyne Type Foundry.

Get it




Collective #535 was written by Pedro Botelho and published on Codrops.


Source: Codrops, Collective #535

Designing And Building A Progressive Web Application Without A Framework (Part 2)

dreamt up by webguru in Uncategorized | Comments Off on Designing And Building A Progressive Web Application Without A Framework (Part 2)

Designing And Building A Progressive Web Application Without A Framework (Part 2)

Designing And Building A Progressive Web Application Without A Framework (Part 2)

Ben Frain



The raison d’être of this adventure was to push your humble author a little in the disciplines of visual design and JavaScript coding. The functionality of the application I’d decided to build was not dissimilar to a ‘to do’ application. It is important to stress that this wasn’t an exercise in original thinking. The destination was far less important than the journey.

Want to find out how the application ended up? Point your phone browser at https://io.benfrain.com.

Read Part One of Designing And Building A Progessive Web Application Without A Framework.

Here is a summary of what we will cover in this article:

  • The project set-up and why I opted for Gulp as a build tool;
  • Application design patterns and what they mean in practice;
  • How to store and visualize application state;
  • how CSS was scoped to components;
  • what UI/UX niceties were employed to make the things more ‘app-like’;
  • How the remit changed through iteration.

Let’s start with the build tools.

Build Tools

In order to get my basic tooling of TypeScipt and PostCSS up and running and create a decent development experience, I would need a build system.

In my day job, for the last five years or so, I have been building interface prototypes in HTML/CSS and to a lesser extent, JavaScript. Until recently, I have used Gulp with any number of plugins almost exclusively to achieve my fairly humble build needs.

Typically I need to process CSS, convert JavaScript or TypeScript to more widely supported JavaScript, and occasionally, carry out related tasks like minifying code output and optimizing assets. Using Gulp has always allowed me to solve those issues with aplomb.

For those unfamiliar, Gulp lets you write JavaScript to do ‘something’ to files on your local file system.
To use Gulp, you typically have a single file (called gulpfile.js) in the root of your project. This JavaScript file allows you to define tasks as functions. You can add third-party ‘Plugins’, which are essentially further JavaScript functions, that deal with specific tasks.

An Example Gulp Task

An example Gulp task might be using a plugin to harness PostCSS to process to CSS when you change an authoring style sheet (gulp-postcss). Or compiling TypeScript files to vanilla JavaScript (gulp-typescript) as you save them. Here is a simple example of how you write a task in Gulp. This task uses the ‘del’ gulp plugin to delete all the files in a folder called ‘build’:

var del = require("del");

gulp.task("clean", function() {
  return del(["build/**/*"]);
});

The require assigns the del plugin to a variable. Then the gulp.task method is called. We name the task with a string as the first argument (“clean”) and then run a function, which in this case uses the ‘del’ method to delete the folder passed to it as an argument. The asterisk symbols there are ‘glob’ patterns which essentially say ‘any file in any folder’ of the build folder.

Gulp tasks can get heaps more complicated but in essence, that is the mechanics of how things are handled. The truth is, with Gulp, you don’t need to be a JavaScript wizard to get by; grade 3 copy and paste skills are all you need.

I’d stuck with Gulp as my default build tool/task runner for all these years with a policy of ‘if it ain’t broke; don’t try and fix it’.

However, I was worried I was getting stuck in my ways. It’s an easy trap to fall into. First, you start holidaying the same place every year, then refusing to adopt any new fashion trends before eventually and steadfastly refusing to try out any new build tools.

I’d heard plenty of chatter on the Internets about ‘Webpack’ and thought it was my duty to try a project using the new-fangled toast of the front-end developer cool-kids.

Webpack

I distinctly remember skipping over to the webpack.js.org site with keen interest. The first explanation of what Webpack is and does started like this:

import bar from './bar';

Say what? In the words of Dr. Evil, “Throw me a frickin’ bone here, Scott”.

I know it’s my own hang-up to deal with but I’ve developed a revulsion to any coding explanations that mention ‘foo’, ‘bar’ or ‘baz’. That plus the complete lack of succinctly describing what Webpack was actually for had me suspecting it perhaps wasn’t for me.

Digging a little further into the Webpack documentation, a slightly less opaque explanation was offered, “At its core, webpack is a static module bundler for modern JavaScript applications”.

Hmmm. Static module bundler. Was that what I wanted? I wasn’t convinced. I read on but the more I read, the less clear I was. Back then, concepts like dependency graphs, hot module reloading, and entry points were essentially lost on me.

A couple of evenings of researching Webpack later, I abandoned any notion of using it.

I’m sure in the right situation and more experienced hands, Webpack is immensely powerful and appropriate but it seemed like complete overkill for my humble needs. Module bundling, tree-shaking, and hot-module reloading sounded great; I just wasn’t convinced I needed them for my little ‘app’.

So, back to Gulp then.

On the theme of not changing things for change sake, another piece of technology I wanted to evaluate was Yarn over NPM for managing project dependencies. Until that point, I had always used NPM and Yarn was getting touted as a better, faster alternative. I don’t have much to say about Yarn other than if you are currently using NPM and everything is OK, you don’t need to bother trying Yarn.

One tool that arrived too late for me to appraise for this application is Parceljs. With zero configuration and a BrowserSync like browser reloading backed in, I’ve since found great utility in it! In addition, in Webpack’s defense, I’m told that v4 onwards of Webpack doesn’t require a configuration file. Anecdotally, in a more recent poll I ran on Twitter, of the 87 respondents, over half chose Webpack over Gulp, Parcel or Grunt.

I started my Gulp file with basic functionality to get up and running.

A ‘default’ task would watch the ‘source’ folders of style sheets and TypeScript files and compile them out to a build folder along with the basic HTML and associated source maps.

I got BrowserSync working with Gulp too. I might not know what to do with a Webpack configuration file but that didn’t mean I was some kind of animal. Having to manually refresh the browser while iterating with HTML/CSS is soooo 2010 and BrowserSync gives you that short feedback and iteration loop that is so useful for front-end coding.

Here is the basic gulp file as of 11.6.2017

You can see how I tweaked the Gulpfile nearer to the end of shipping, adding minification with ugilify:

Project Structure

By consequence of my technology choices, some elements of code organization for the application were defining themselves. A gulpfile.js in the root of the project, a node_modules folder (where Gulp stores plugin code) a preCSS folder for the authoring style sheets, a ts folder for the TypeScript files, and a build folder for the compiled code to live.

The idea was to have an index.html that contained the ‘shell’ of the application, including any non-dynamic HTML structure and then links to the styles and the JavaScript file that would make the application work. On disk, it would look something like this:

build/
node_modules/
preCSS/
    img/
    partials/
    styles.css
ts/
.gitignore
gulpfile.js
index.html
package.json
tsconfig.json

Configuring BrowserSync to look at that build folder meant I could point my browser at localhost:3000 and all was good.

With a basic build system in place, files organization settled and some basic designs to make a start with, I had run-out of procrastination fodder I could legitimately use to prevent me from actually building the thing!

Writing An Application

The principle of how the application would work was this. There would be a store of data. When the JavaScript loaded it would load that data, loop through each player in the data, creating the HTML needed to represent each player as a row in the layout and placing them in the appropriate in/out section. Then interactions from the user would move a player from one state to another. Simple.

When it came to actually writing the application, the two big conceptual challenges that needed to be understood were:

  1. How to represent the data for an application in a manner that could be easily extended and manipulated;
  2. How to make the UI react when data was changed from user input.

One of the simplest ways to represent a data structure in JavaScript is with object notation. That sentence reads a little computer science-y. More simply, an ‘object’ in JavaScript lingo is a handy way of storing data.

Consider this JavaScript object assigned to a variable called ioState (for In/Out State):

var ioState = {
    Count: 0, // Running total of how many players
    RosterCount: 0; // Total number of possible players
    ToolsExposed: false, // Whether the UI for the tools is showing
    Players: [], // A holder for the players
}

If you don’t really know JavaScript that well, you can probably at least grasp what’s going on: each line inside the curly braces is a property (or ‘key’ in JavaScript parlance) and value pair. You can set all sorts of things to a JavaScript key. For example, functions, arrays of other data or nested objects. Here’s an example:

var testObject = {
  testFunction: function() {
    return "sausages";
  },
  testArray: [3,7,9],
  nestedtObject {
    key1: "value1",
    key2: 2,
  }
}

The net result is that using that kind of data structure you can get, and set, any of the keys of the object. For example, if we want to set the count of the ioState object to 7:

ioState.Count = 7;

If we want to set a piece of text to that value, the notation works like this:

aTextNode.textContent = ioState.Count;

You can see that getting values and setting values to that state object is simple in the JavaScript side of things. However, reflecting those changes in the User Interface is less so. This is the main area where frameworks and libraries seek to abstract away the pain.

In general terms, when it comes to dealing with updating the user interface based upon state, it’s preferable to avoid querying the DOM, as this is generally considered a sub-optimal approach.

Consider the In/Out interface. It’s typically showing a list of potential players for a game. They are vertically listed, one under the other, down the page.

Perhaps each player is represented in the DOM with a label wrapping a checkbox input. This way, clicking a player would toggle the player to ‘In’ by virtue of the label making the input ‘checked’.

To update our interface, we might have a ‘listener’ on each input element in the JavaScript. On a click or change, the function queries the DOM and counts how many of our player inputs are checked. On the basis of that count, we would then update something else in the DOM to show the user how many players are checked.

Let’s consider the cost of that basic operation. We are listening on multiple DOM nodes for the click/check of an input, then querying the DOM to see how many of a particular DOM type are checked, then writing something into the DOM to show the user, UI wise, the number of players we just counted.

The alternative would be to hold the application state as a JavaScript object in memory. A button/input click in the DOM could merely update the JavaScript object and then, based on that change in the JavaScript object, do a single-pass update of the all interface changes that are needed. We could skip querying the DOM to count the players as the JavaScript object would already hold that information.

So. Using a JavaScript object structure for the state seemed simple but flexible enough to encapsulate the application state at any given time. The theory of how this could be managed seemed sound enough too – this must be what phrases like ‘one-way data flow’ were all about? However, the first real trick would be in creating some code that would automatically update the UI based on any changes to that data.

The good news is that smarter people than I have already figured this stuff out (thank goodness!). People have been perfecting approaches to this kind of challenge since the dawn of applications. This category of problems is the bread and butter of ‘design patterns’. The moniker ‘design pattern’ sounded esoteric to me at first but after digging just a little it all started to sound less computer science and more common sense.

Design Patterns

A design pattern, in computer science lexicon, is a pre-defined and proven way of solving a common technical challenge. Think of design patterns as the coding equivalent of a cooking recipe.

Perhaps the most famous literature on design patterns is “Design Patterns: Elements of Reusable Object-Oriented Software” from back in 1994. Although that deals with C++ and smalltalk the concepts are transferable. For JavaScript, Addy Osmani’s “Learning JavaScript Design Patterns” covers similar ground. You can also read it online for free here.

Observer Pattern

Typically design patterns are split into three groups: Creational, Structural and Behavioural. I was looking for something Behavioural that helped to deal with communicating changes around the different parts of the application.

More recently, I have seen and read a really great deep-dive on implementing reactivity inside an app by Gregg Pollack. There is both a blog post and video for your enjoyment here.

When reading the opening description of the ‘Observer’ pattern in Learning JavaScript Design Patterns I was pretty sure it was the pattern for me. It is described thus:

The Observer is a design pattern where an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state.

When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers (which can include specific data related to the topic of the notification).

The key to my excitement was that this seemed to offer some way of things updating themselves when needed.

Suppose the user clicked a player named “Betty” to select that she was ‘In’ for the game. A few things might need to happen in the UI:

  1. Add 1 to the playing count
  2. Remove Betty from the ‘Out’ pool of players
  3. Add Betty to the ‘In’ pool of players

The app would also need to update the data that represented the UI. What I was very keen to avoid was this:

playerName.addEventListener("click", playerToggle);

function playerToggle() {
  if (inPlayers.includes(e.target.textContent)) {
    setPlayerOut(e.target.textContent);
    decrementPlayerCount();
  } else {
    setPlayerIn(e.target.textContent);
    incrementPlayerCount();
  }
}

The aim was to have an elegant data flow that updated what was needed in the DOM when and if the central data was changed.

With an Observer pattern, it was possible to send out updates to the state and therefore the user interface quite succinctly. Here is an example, the actual function used to add a new player to the list:

function itemAdd(itemString: string) {
  let currentDataSet = getCurrentDataSet();
  var newPerson = new makePerson(itemString);
  io.items[currentDataSet].EventData.splice(0, 0, newPerson);
  io.notify({
    items: io.items
  });
}

The part relevant to the Observer pattern there being the io.notify method. As that shows us modifying the items part of the application state, let me show you the observer that listened for changes to ‘items’:

io.addObserver({
  props: ["items"],
  callback: function renderItems() {
    // Code that updates anything to do with items...
  }
});

We have a notify method that makes changes to the data and then Observers to that data that respond when properties they are interested in are updated.

With this approach, the app could have observables watching for changes in any property of the data and run a function whenever a change occurred.

If you are interested in the Observer pattern I opted for, I describe it more fully here.

There was now an approach for updating the UI effectively based on state. Peachy. However, this still left me with two glaring issues.

One was how to store the state across page reloads/sessions and the fact that despite the UI working, visually, it just wasn’t very ‘app like’. For example, if a button was pressed the UI instantly changed on screen. It just wasn’t particularly compelling.

Let’s deal with the storage side of things first.

Saving State

My primary interest from a development side entering into this centered on understanding how app interfaces could be built and made interactive with JavaScript. How to store and retrieve data from a server or tackle user-authentication and logins was ‘out of scope’.

Therefore, instead of hooking up to a web service for the data storage needs, I opted to keep all data on the client. There are a number of web platform methods of storing data on a client. I opted for localStorage.

The API for localStorage is incredibly simple. You set and get data like this:

// Set something
localStorage.setItem("yourKey", "yourValue");
// Get something
localStorage.getItem("yourKey");

LocalStorage has a setItem method that you pass two strings to. The first is the name of the key you want to store the data with and the second string is the actual string you want to store. The getItem method takes a string as an argument that returns to you whatever is stored under that key in localStorage. Nice and simple.

However, amongst the reasons to not use localStorage is the fact that everything has to be saved as a ‘string’. This means you can’t directly store something like an array or object. For example, try running these commands in your browser console:

// Set something
localStorage.setItem("myArray", [1, 2, 3, 4]);
// Get something
localStorage.getItem("myArray"); // Logs "1,2,3,4"

Even though we tried to set the value of ‘myArray’ as an array; when we retrieved it, it had been stored as a string (note the quote marks around ‘1,2,3,4’).

You can certainly store objects and arrays with localStorage but you need to be mindful that they need converting back and forth from strings.

So, in order to write state data into localStorage it was written to a string with the JSON.stringify() method like this:

const storage = window.localStorage;
storage.setItem("players", JSON.stringify(io.items));

When the data needed retrieving from localStorage, the string was turned back into usable data with the JSON.parse() method like this:

const players = JSON.parse(storage.getItem("players"));

Using localStorage meant everything was on the client and that meant no 3rd party services or data storage concerns.

Data was now persisting refreshes and sessions — Yay! The bad news was that localStorage does not survive a user emptying their browser data. When someone did that, all their In/Out data would be lost. That’s a serious shortcoming.

It’s not hard to appreciate that `localStorage` probably isn’t the best solution for ‘proper’ applications. Besides the aforementioned string issue, it is also slow for serious work as it blocks the ‘main thread’. Alternatives are coming, like KV Storage but for now, make a mental note to caveat its use based on suitability.

Despite the fragility of saving data locally on a users device, hooking up to a service or database was resisted. Instead, the issue was side-stepped by offering a ‘load/save’ option. This would allow any user of In/Out to save their data as a JSON file which could be loaded back into the app if needed.

This worked well on Android but far less elegantly for iOS. On an iPhone, it resulted in a splurge of text on screen like this:

On an iPhone, it resulted in a splurge of text on screen

(Large preview)

As you can imagine, I was far from alone in berating Apple via WebKit about this shortcoming. The relevant bug was here.

At the time of writing this bug has a solution and patch but has yet to make its way into iOS Safari. Allegedly, iOS13 fixes it but it’s that’s in Beta as I write.

So, for my minimum viable product, that was storage addressed. Now it was time to attempt to make things more ‘app-like’!

App-I-Ness

Turns out after many discussions with many people, defining exactly what ‘app like’ means is quite difficult.

Ultimately, I settled on ‘app-like’ being synonymous with a visual slickness usually missing from the web. When I think of the apps that feel good to use they all feature motion. Not gratuitous, but motion that adds to the story of your actions. It might be the page transitions between screens, the manner in which menus pop into existence. It’s hard to describe in words but most of us know it when we see it.

The first piece of visual flair needed was shifting player names up or down from ‘In’ to ‘Out’ and vice-versa when selected. Making a player instantly move from one section to the other was straightforward but certainly not ‘app-like’. An animation as a player name was clicked would hopefully emphasize the result of that interaction – the player moving from one category to another.

Like many of these kinds of visual interactions, their apparent simplicity belies the complexity involved in actually getting it working well.

It took a few iterations to get the movement right but the basic logic was this:

  • Once a ‘player’ is clicked, capture where that player is, geometrically, on the page;
  • Measure how far away the top of the area is the player needs to move to if going up (‘In’) and how far away the bottom is, if going down (‘Out’);
  • If going up, a space equal to the height of the player row needs to be left as the player moves up and the players above should collapse downwards at the same rate as the time it takes for the player to travel up to land in the space vacated by the existing ‘In’ players (if any exist) coming down;
  • If a player is going ‘Out’ and moving down, everything else needs to move up to the space left and the player needs to end up below any current ‘Out’ players.

Phew! It was trickier than I thought in English — never mind JavaScript!

There were additional complexities to consider and trial such as transition speeds. At the outset, it wasn’t obvious whether a constant speed of movement (e.g. 20px per 20ms), or a constant duration for the movement (e.g. 0.2s) would look better. The former was slightly more complicated as the speed needed to be computed ‘on the fly’ based upon how far the player needed to travel — greater distance requiring a longer transition duration.

However, it turned out that a constant transition duration was not just simpler in code; it actually produced a more favorable effect. The difference was subtle but these are the kind of choices you can only determine once you have seen both options.

Every so often whilst trying to nail this effect, a visual glitch would catch the eye but it was impossible to deconstruct in real time. I found the best debugging process was creating a QuickTime recording of the animation and then going through it a frame at a time. Invariably this revealed the problem quicker than any code based debugging.

Looking at the code now, I can appreciate that on something beyond my humble app, this functionality could almost certainly be written more effectively. Given that the app would know the number of players and know the fixed height of the slats, it should be entirely possible to make all distance calculations in the JavaScript alone, without any DOM reading.

It’s not that what was shipped doesn’t work, it’s just that it isn’t the kind of code solution you would showcase on the Internet. Oh, wait.

Other ‘app like’ interactions were much easier to pull off. Instead of menus simply snapping in and out with something as simple as toggling a display property, a lot of mileage was gained by simply exposing them with a little more finesse. It was still triggered simply but CSS was doing all the heavy lifting:

.io-EventLoader {
  position: absolute;
  top: 100%;
  margin-top: 5px;
  z-index: 100;
  width: 100%;
  opacity: 0;
  transition: all 0.2s;
  pointer-events: none;
  transform: translateY(-10px);
  [data-evswitcher-showing="true"] & {
    opacity: 1;
    pointer-events: auto;
    transform: none;
  }
}

There when the data-evswitcher-showing="true" attribute was toggled on a parent element, the menu would fade in, transform back into its default position and pointer events would be re-enabled so the menu could receive clicks.

ECSS Style Sheet Methodology

You’ll notice in that prior code that from an authoring point of view, CSS overrides are being nested within a parent selector. That’s the way I always favor writing UI style sheets; a single source of truth for each selector and any overrides for that selector encapsulated within a single set of braces. It’s a pattern that requires the use of a CSS processor (Sass, PostCSS, LESS, Stylus, et al) but I feel is the only positive way to make use of nesting functionality.

I’d cemented this approach in my book, Enduring CSS and despite there being a plethora of more involved methods available to write CSS for interface elements, ECSS has served me and the large development teams I work with well since the approach was first documented way back in 2014! It proved just as effective in this instance.

Partialling The TypeScript

Even without a CSS processor or superset language like Sass, CSS has had the ability to import one or more CSS files into another with the import directive:

@import "other-file.css";

When beginning with JavaScript I was surprised there was no equivalent. Whenever code files get longer than a screen or so high, it always feels like splitting it into smaller pieces would be beneficial.

Another bonus to using TypeScript was that it has a beautifully simple way of splitting code into files and importing them when needed.

This capability pre-dated native JavaScript modules and was a great convenience feature. When TypeScript was compiled it stitched it all back to a single JavaScript file. It meant it was possible to easily break up the application code into manageable partial files for authoring and import then into the main file easily. The top of the main inout.ts looked like this:

/// <reference path="defaultData.ts" />
/// <reference path="splitTeams.ts" />
/// <reference path="deleteOrPaidClickMask.ts" />
/// <reference path="repositionSlat.ts" />
/// <reference path="createSlats.ts" />
/// <reference path="utils.ts" />
/// <reference path="countIn.ts" />
/// <reference path="loadFile.ts" />
/// <reference path="saveText.ts" />
/// <reference path="observerPattern.ts" />
/// <reference path="onBoard.ts" />

This simple house-keeping and organization task helped enormously.

Multiple Events

At the outset, I felt that from a functionality point of view, a single event, like “Tuesday Night Football” would suffice. In that scenario, if you loaded In/Out up you just added/removed or moved players in or out and that was that. There was no notion of multiple events.

I quickly decided that (even going for a minimum viable product) this would make for a pretty limited experience. What if somebody organized two games on different days, with a different roster of players? Surely In/Out could/should accommodate that need?
It didn’t take too long to re-shape the data to make this possible and amend the methods needed to load in a different set.

At the outset, the default data set looked something like this:

var defaultData = [
  { name: "Daz", paid: false, marked: false, team: "", in: false },
  { name: "Carl", paid: false, marked: false, team: "", in: false },
  { name: "Big Dave", paid: false, marked: false, team: "", in: false },
  { name: "Nick", paid: false, marked: false, team: "", in: false }
];

An array containing an object for each player.

After factoring in multiple events it was amended to look like this:

var defaultDataV2 = [
  {
    EventName: "Tuesday Night Footy",
    Selected: true,
    EventData: [
      { name: "Jack", marked: false, team: "", in: false },
      { name: "Carl", marked: false, team: "", in: false },
      { name: "Big Dave", marked: false, team: "", in: false },
      { name: "Nick", marked: false, team: "", in: false },
      { name: "Red Boots", marked: false, team: "", in: false },
      { name: "Gaz", marked: false, team: "", in: false },
      { name: "Angry Martin", marked: false, team: "", in: false }
    ]
  },
  {
    EventName: "Friday PM Bank Job",
    Selected: false,
    EventData: [
      { name: "Mr Pink", marked: false, team: "", in: false },
      { name: "Mr Blonde", marked: false, team: "", in: false },
      { name: "Mr White", marked: false, team: "", in: false },
      { name: "Mr Brown", marked: false, team: "", in: false }
    ]
  },
  {
    EventName: "WWII Ladies Baseball",
    Selected: false,
    EventData: [
      { name: "C Dottie Hinson", marked: false, team: "", in: false },
      { name: "P Kit Keller", marked: false, team: "", in: false },
      { name: "Mae Mordabito", marked: false, team: "", in: false }
    ]
  }
];

The new data was an array with an object for each event. Then in each event was an EventData property that was an array with player objects in as before.

It took much longer to re-consider how the interface could best deal with this new capability.

From the outset, the design had always been very sterile. Considering this was also supposed to be an exercise in design, I didn’t feel I was being brave enough. So a little more visual flair was added, starting with the header. This is what I mocked up in Sketch:

A mockup of the revised app design

Revised design mockup. (Large preview)

It wasn’t going to win awards but it was certainly more arresting than where it started.

Aesthetics aside, it wasn’t until somebody else pointed it out, that I appreciated the big plus icon in the header was very confusing. Most people thought it was a way to add another event. In reality, it switched to an ‘Add Player’ mode with a fancy transition that let you type in the name of the player in the same place the event name was currently.

This was another instance where fresh eyes were invaluable. It was also an important lesson in letting go. The honest truth was I had held on to the input mode transition in the header because I felt it was cool and clever. However, the fact was it was not serving the design and therefore the application as a whole.

This was changed in the live version. Instead, the header just deals with events — a more common scenario. Meanwhile, adding players is done from a sub-menu. This gives the app a much more understandable hierarchy.

The other lesson learned here was that whenever possible, it’s hugely beneficial to get candid feedback from peers. If they are good and honest people, they won’t let you give yourself a pass!

Summary: My Code Stinks

Right. So far, so normal tech-adventure retrospective piece; these things are ten a penny on Medium! The formula goes something like this: the dev details how they smashed down all obstacles to release a finely tuned piece of software into the Internets and then pick up an interview at Google or got acqui-hired somewhere. However, the truth of the matter is that I was a first-timer at this app-building malarkey so the code ultimately shipped as the ‘finished’ application stunk to high heaven!

For example, the Observer pattern implementation used worked very well. I was organized and methodical at the outset but that approach ‘went south’ as I became more desperate to finish things off. Like a serial dieter, old familiar habits crept back in and the code quality subsequently dropped.

Looking now at the code shipped, it is a less than ideal hodge-bodge of clean observer pattern and bog-standard event listeners calling functions. In the main inout.ts file there are over 20 querySelector method calls; hardly a poster child for modern application development!

I was pretty sore about this at the time, especially as at the outset I was aware this was a trap I didn’t want to fall into. However, in the months that have since passed, I’ve become more philosophical about it.

The final post in this series reflects on finding the balance between silvery-towered code idealism and getting things shipped. It also covers the most important lessons learned during this process and my future aspirations for application development.

Smashing Editorial
(dm, yk, il, ra)

Source: Smashing Magazine, Designing And Building A Progressive Web Application Without A Framework (Part 2)

Created To Make You Think: Meet Our New Printed Magazine

dreamt up by webguru in Uncategorized | Comments Off on Created To Make You Think: Meet Our New Printed Magazine

Created To Make You Think: Meet Our New Printed Magazine

Created To Make You Think: Meet Our New Printed Magazine

Vitaly Friedman



For a long time, we wanted to create a printed magazine that hasn’t existed before. Not a magazine about fleeting design trends or ever-changing frameworks, but topics that would make us all think, and that would remain useful as time passes. A printed magazine exploring topics that often get lost in the myriad of blog posts out there.

About the Magazine

With Smashing Magazine Print, we want to provide a space for topics that perhaps have more longevity than what we usually cover online — without running short on practical and actionable insights, of course. One theme per issue, with handy, digestible 6080 pages of high-quality print, containing a handful of curated and unpublished articles.

Approachable, friendly and inclusive. Written by and for the community, with a focus on real-world insights and the challenges that we all have to tackle together — for people just like you, who design and build the web. It took us more time than expected, but we are done now, and shipping worldwide. Download a free PDF preview (3 MB) and get your copy now.


The cover of Smashing Magazine Print.


The cover of Smashing Magazine Print.

Print

$ 17.50 $ 24.95Get Smashing Print

Printed magazine + PDF, ePUB, Kindle.
Free airmail shipping worldwide.

Print + Membership

$ 9 / mo.Become a Smasher

Printed magazine for free + DRM-free eBooks, webinars and other fancy things.

All Smashing Members ($5 per month) get the eBook for free, and Smashers ($9 plan) also get a free printed copy shipped to the doorsteps. For additional copies, a discount of $10 applies.

About the Issue

We kick off with an issue exploring topics very close to our hearts — ethics, privacy and security, because these issues reach into all our lives, from our personal use of the web through to the advanced applications we develop. We take a closer look at the current state of tracking, advertising, GDPR and privacy law, data protection and addictive interfaces. We explore how we all can integrate privacy-driven decisions into our workflows by default, abandoning dark patterns for good along the way.


Connecting the dots, an illustration for the table of contents of the Smashing Magazine Print, with chapters connected with dots.
The table of contents of the shiny new printed magazine. Peek inside! (PDF).

The web is wonderfully diverse and unpredictable because of the wonderfully diverse people who shape it. While we often see people as lifeless dots in our analytics stats, every single dot is an actual person, and so every single dot matters. We deserve to be respected and valued, and that holds true for how companies treat our data and privacy, too. In times when humility and kindness have become rarities, we need to find a way to make the web a calmer, more respectful place that treats data and privacy seriously?

That’s what we wanted to explore. So, we got to work. We’ve teamed up with Veerle Pieters for the design and illustrations, and Rachel has been working with the authors to bring valuable insights to the magazine. Rather than asking the authors to write on very specific topics, Rachel asked them to contribute to a collection of thinking on the subjects of ethics, privacy and security.

Table of Contents

What follows is a collection of articles that sit very well together, yet tackle different aspects of the issues at hand. You might not agree with all of them, but we hope they will make you think.

  1. Editor’s Note
    by Rachel Andrew
  2. Towards Ethics By Default, One Step at a Time
    by Vitaly Friedman
  3. Designing For Addiction
    by Trine Falbe
  4. It’s Not About You
    by Heather Burns and Morten Rand-Hendriksen
  5. This One Weird Trick Tells Us Everything About You
    by Laura Kalbag
  6. Quieting Disquiet
    by Stuart Langridge
  7. Advertising Is Not The Problem
    by Cennydd Bowles

Along with the themed articles, we have included some little insights into our Smashing Family, pieces about our books, conferences and membership. You might not know it, but Smashing Magazine is brought to you by a tiny team of people who care. We care about the values we stand behind, and about the people who read the magazine, who join as members, and who come to conferences. We care a lot about the web. We hope that shines through in everything we do.

60 pages. High-quality print. Free worldwide airmail shipping from Germany, late July. Written by and for the community. Download a free PDF preview (3 MB).


The cover of Smashing Magazine Print

Print

$ 17.50 $ 24.95Get Smashing Print

Printed magazine + PDF, ePUB, Kindle.
Free airmail shipping worldwide.

Print + Membership

$ 9 / mo.Become a Smasher

Printed magazine for free + DRM-free eBooks, webinars and other fancy things.

Community Matters ❤️

The printed magazine wouldn’t exist without our dear Smashing community, and that’s why it is and always will be free to Smashing Members.

  • If you haven’t heard of the Membership yet, no worries: you are awesome just the way you are, and you can join our wonderful community any time. We can’t wait to see you!
  • If you are a Supporter ($3 plan), please don’t forget to sign in for your discount to be applied automatically.
  • If you are a Member ($5 plan), please sign in and download the digital version on the product page. Obviously, you also get a discount on the printed copy.
  • If you’re a Smasher ($9 plan), please sign in and save your shipping address, and we’ll ship the book to your doorsteps right away. Also, feel free to download the digital version on the product page.
The cover of Smashing Magazine Print
Our brand-new printed magazine is free for Smashing Members (eBook with the $5 plan, Print + eBook with $9 plan). You can cancel any time, you know.

Admittedly, publishing a printed magazine in a time when everything has gone digital is quite a gamble for us. But you never know for sure until you try — and fail or succeed.

We don’t know how the magazine will take shape in the future, but we already can’t wait to hear your feedback. We’re very excited, and we hope you’ll be, too —at least when you hold the very first issue of the printed magazine in your hands.

Stay smashing, and thank you for your ongoing support, everyone!

Smashing Editorial
(vf, al, il)

Source: Smashing Magazine, Created To Make You Think: Meet Our New Printed Magazine

Smashing TV Live: Towards Ethics & Privacy By Default

dreamt up by webguru in Uncategorized | Comments Off on Smashing TV Live: Towards Ethics & Privacy By Default

Smashing TV Live: Towards Ethics & Privacy By Default

Smashing TV Live: Towards Ethics & Privacy By Default

Vitaly Friedman



Honesty, humility and authenticity became rarities on the web. Dark patterns are prevailing many of the interfaces we use, and our data is collected, evaluated and handed over to third-parties left and right, often without us noticing at all. To many of our customers it’s not really a big deal — privacy is often seen as a fair price for using all the wonderful free services around us.

However, we might underestimate the value of data we willingly hand over to data-driven companies. And very often, while we mindlessly click away a cookie consent prompt, we are giving away the sense of intimacy. After all, nobody loves to search for shoes one day, and be followed by the same shoes across the entire web over weeks to come.


Watch the session
Smashing TV: “Towards Privacy By Default”, a conversation, moderated by Vitaly Friedman. With Trine Falbe, Laura Kalbag, Heather Burns, Cennydd Bowles, Stuart Langridge and Morten Rand-Hendriksen.

Join the live stream @ Today, 1PM GMT ↬

In the panel discussion, we look into:

  • How do we deal with advertising, tracking, sensitive data collection and treatment of data?
  • How do we “sell” ethics and privacy to managers and clients?
  • How do we change the culture of dark patterns in our interfaces?
  • How and when do we integrate privacy, ethics, security in our design/dev workflows?
  • How do we maintain privacy and ethics over time?
  • How does GDPR help us shift the culture on the web?

These aren’t easy questions to answer, and we need reliable solutions to make the difference. But we can figure out a way forward, and how to make privacy-aware decisions a default in our design and development work. These are also the questions we explore in our brand-new Smashing Magazine Print. In fact, it’s the magazine that prompted us to run a live session in the first place.

Meet Our New Printed Magazine

With Smashing Magazine Print, we want to provide a space for important topics that perhaps have more longevity than what we usually cover online — without running short on practical and actionable insights, of course.

We kick off with a 60-pages issue exploring ethics, privacy and security. We take a closer look at the current state of tracking, advertising, GDPR and privacy law, data protection and addictive interfaces. We explore how we all can integrate privacy-driven decisions into our workflows by default, abandoning dark patterns for good along the way.

And — guess what! — it’s ready now, and it’s shipping worldwide. Download a free PDF preview (3 MB) and get your copy now.


The cover of Smashing Magazine Print.


The cover of Smashing Magazine Print.

Print

$ 17.50 $ 24.95Get Smashing Print

Printed magazine + PDF, ePUB, Kindle.
Free airmail shipping worldwide.

Print + Membership

$ 9 / mo.Become a Member

Printed magazine for free + eBooks, webinars, discounts and other fancy things.

Rewatch The Recording!

And that’s a wrap! Watch the recording with Trine Falbe, Laura Kalbag, Heather Burns, Cennydd Bowles, Stuart Langridge and Morten Rand-Hendriksen. Also, prepare and post your questions and we’ll bring them up during the discussion as well, of course!

Watch the recording ↬

Smashing Editorial
(dm, og, il)

Source: Smashing Magazine, Smashing TV Live: Towards Ethics & Privacy By Default

Designing And Building A Progressive Web Application Without A Framework (Part 1)

dreamt up by webguru in Uncategorized | Comments Off on Designing And Building A Progressive Web Application Without A Framework (Part 1)

Designing And Building A Progressive Web Application Without A Framework (Part 1)

Designing And Building A Progressive Web Application Without A Framework (Part 1)

Ben Frain



How does a web application actually work? I don’t mean from the end-user point of view. I mean in the technical sense. How does a web application actually run? What kicks things off? Without any boilerplate code, what’s the right way to structure an application? Particularly a client-side application where all the logic runs on the end-users device. How does data get managed and manipulated? How do you make the interface react to changes in the data?

These are the kind of questions that are simple to side-step or ignore entirely with a framework. Developers reach for something like React, Vue, Ember or Angular, follow the documentation to get up and running and away they go. Those problems are handled by the framework’s box of tricks.

That may be exactly how you want things. Arguably, it’s the smart thing to do if you want to build something to a professional standard. However, with the magic abstracted away, you never get to learn how the tricks are actually performed.

Don’t you want to know how the tricks are done?

I did. So, I decided to try building a basic client-side application, sans-framework, to understand these problems for myself.

But, I’m getting a little ahead of myself; a little background first.

Before starting this journey I considered myself highly proficient at HTML and CSS but not JavaScript. As I felt I’d solved the biggest questions I had of CSS to my satisfaction, the next challenge I set myself was understanding a programming language.

The fact was, I was relatively beginner-level with JavaScript. And, aside from hacking the PHP of WordPress around, I had no exposure or training in any other programming language either.

Let me qualify that ‘beginner-level’ assertion. Sure, I could get interactivity working on a page. Toggle classes, create DOM nodes, append and move them around, etc. But when it came to organizing the code for anything beyond that I was pretty clueless. I wasn’t confident building anything approaching an application. I had no idea how to define a set of data in JavaScipt, let alone manipulate it with functions.

I had no understanding of JavaScript ‘design patterns’ — established approaches for solving oft-encountered code problems. I certainly didn’t have a feel for how to approach fundamental application-design decisions.

Have you ever played ‘Top Trumps’? Well, in the web developer edition, my card would look something like this (marks out of 100):

  • CSS: 95
  • Copy and paste: 90
  • Hairline: 4
  • HTML: 90
  • JavaSript: 13

In addition to wanting to challenge myself on a technical level, I was also lacking in design chops.

With almost exclusively coding other peoples designs for the past decade, my visual design skills hadn’t had any real challenges since the late noughties. Reflecting on that fact and my puny JavaScript skills, cultivated a growing sense of professional inadequacy. It was time to address my shortcomings.

A personal challenge took form in my mind: to design and build a client-side JavaScript web application.

On Learning

There has never been more great resources to learn computing languages. Particularly JavaScript. However, it took me a while to find resources that explained things in a way that clicked. For me, Kyle Simpson’s ‘You Don’t Know JS’ and ‘Eloquent JavaScript’ by Marijn Haverbeke were a big help.

If you are beginning learning JavaScript, you will surely need to find your own gurus; people whose method of explaining works for you.

The first key thing I learned was that it’s pointless trying to learn from a teacher/resource that doesn’t explain things in a way you understand. Some people look at function examples with foo and bar in and instantly grok the meaning. I’m not one of those people. If you aren’t either, don’t assume programming languages aren’t for you. Just try a different resource and keep trying to apply the skills you are learning.

It’s also not a given that you will enjoy any kind of eureka moment where everything suddenly ‘clicks’; like the coding equivalent of love at first sight. It’s more likely it will take a lot of perseverance and considerable application of your learnings to feel confident.

As soon as you feel even a little competent, trying to apply your learning will teach you even more.

Here are some resources I found helpful along the way:

Right, that’s pretty much all you need to know about why I arrived at this point. The elephant now in the room is, why not use a framework?

Why Not React, Ember, Angular, Vue Et Al

Whilst the answer was alluded to at the beginning, I think the subject of why a framework wasn’t used needs expanding upon.

There are an abundance of high quality, well supported, JavaScript frameworks. Each specifically designed for the building of client-side web applications. Exactly the sort of thing I was looking to build. I forgive you for wondering the obvious: like, err, why not use one?

Here’s my stance on that. When you learn to use an abstraction, that’s primarily what you are learning — the abstraction. I wanted to learn the thing, not the abstraction of the thing.

I remember learning some jQuery back in the day. Whilst the lovely API let me make DOM manipulations easier than ever before I became powerless without it. I couldn’t even toggle classes on an element without needing jQuery. Task me with some basic interactivity on a page without jQuery to lean on and I stumbled about in my editor like a shorn Samson.

More recently, as I attempted to improve my understanding of JavaScript, I’d tried to wrap my head around Vue and React a little. But ultimately, I was never sure where standard JavaScript ended and React or Vue began. My opinion is that these abstractions are far more worthwhile when you understand what they are doing for you.

Therefore, if I was going to learn something I wanted to understand the core parts of the language. That way, I had some transferable skills. I wanted to retain something when the current flavor of the month framework had been cast aside for the next ‘hot new thing’.

Okay. Now, we’re caught up on why this app was getting made, and also, like it or not, how it would be made.

Let’s move on to what this thing was going to be.

An Application Idea

I needed an app idea. Nothing too ambitious; I didn’t have any delusions of creating a business start-up or appearing on Dragon’s Den — learning JavaScript and application basics was my primary goal.

The application needed to be something I had a fighting chance of pulling off technically and making a half-decent design job off to boot.

Tangent time.

Away from work, I organize and play indoor football whenever I can. As the organizer, it’s a pain to mentally note who has sent me a message to say they are playing and who hasn’t. 10 people are needed for a game typically, 8 at a push. There’s a roster of about 20 people who may or may not be able to play each game.

The app idea I settled on was something that enabled picking players from a roster, giving me a count of how many players had confirmed they could play.

As I thought about it more I felt I could broaden the scope a little more so that it could be used to organize any simple team-based activity.

Admittedly, I’d hardly dreamt up Google Earth. It did, however, have all the essential challenges: design, data management, interactivity, data storage, code organization.

Design-wise, I wouldn’t concern myself with anything other than a version that could run and work well on a phone viewport. I’d limit the design challenges to solving the problems on small screens only.

The core idea certainly leaned itself to ‘to-do’ style applications, of which there were heaps of existing examples to look at for inspiration whilst also having just enough difference to provide some unique design and coding challenges.

Intended Features

An initial bullet-point list of features I intended to design and code looked like this:

  • An input box to add people to the roster;
  • The ability to set each person to ‘in’ or ‘out’;
  • A tool that splits the people into teams, defaulting to 2 teams;
  • The ability to delete a person from the roster;
  • Some interface for ‘tools’. Besides splitting, available tools should include the ability to download the entered data as a file, upload previously saved data and delete-all players in one go;
  • The app should show a current count of how many people are ‘In’;
  • If there are no people selected for a game, it should hide the team splitter;
  • Pay mode. A toggle in settings that allows ‘in’ users to have an additional toggle to show whether they have paid or not.

At the outset, this is what I considered the features for a minimum viable product.

Design

Designs started on scraps of paper. It was illuminating (read: crushing) to find out just how many ideas which were incredible in my head turned out to be ludicrous when subjected to even the meagre scrutiny afforded by a pencil drawing.

Many ideas were therefore quickly ruled out, but the flip side was that by sketching some ideas out, it invariably led to other ideas I would never have otherwise considered.

Now, designers reading this will likely be like, “Duh, of course” but this was a real revelation to me. Developers are used to seeing later stage designs, rarely seeing all the abandoned steps along the way prior to that point.

Once happy with something as a pencil drawing, I’d try and re-create it in the design package, Sketch. Just as ideas fell away at the paper and pencil stage, an equal number failed to make it through the next fidelity stage of Sketch. The ones that seemed to hold up as artboards in Sketch were then chosen as the candidates to code out.

I’d find in turn that when those candidates were built-in code, a percentage also failed to work for varying reasons. Each fidelity step exposed new challenges for the design to either pass or fail. And a failure would lead me literally and figuratively back to the drawing board.

As such, ultimately, the design I ended up with is quite a bit different than the one I originally had in Sketch. Here are the first Sketch mockups:

Initial design of Who’s In application

Initial design of Who’s In application (Large preview)

Initial menu for Who’s In application

Initial menu for Who’s In application (Large preview)

Even then, I was under no delusions; it was a basic design. However, at this point I had something I was relatively confident could work and I was chomping at the bit to try and build it.

Technical Requirements

With some initial feature requirements and a basic visual direction, it was time to consider what should be achieved with the code.

Although received wisdom dictates that the way to make applications for iOS or Android devices is with native code, we have already established that my intention was to build the application with JavaScript.

I was also keen to ensure that the application ticked all the boxes necessary to qualify as a Progressive Web Application, or PWA as they are more commonly known.

On the off chance you are unaware what a Progressive Web Application is, here is the ‘elevator pitch’. Conceptually, just imagine a standard web application but one that meets some particular criteria. The adherence to this set of particular requirements means that a supporting device (think mobile phone) grants the web app special privileges, making the web application greater than the sum of its parts.

On Android, in particular, it can be near impossible to distinguish a PWA, built with just HTML, CSS and JavaScript, from an application built with native code.

Here is the Google checklist of requirements for an application to be considered a Progressive Web Application:

  • Site is served over HTTPS;
  • Pages are responsive on tablets & mobile devices;
  • All app URLs load while offline;
  • Metadata provided for Add to Home screen;
  • First load fast even on 3G;
  • Site works cross-browser;
  • Page transitions don’t feel like they block on the network;
  • Each page has a URL.

Now in addition, if you really want to be the teacher’s pet and have your application considered as an ‘Exemplary Progressive Web App’, then it should also meet the following requirements:

  • Site’s content is indexed by Google;
  • Schema.org metadata is provided where appropriate;
  • Social metadata is provided where appropriate;
  • Canonical URLs are provided when necessary;
  • Pages use the History API;
  • Content doesn’t jump as the page loads;
  • Pressing back from a detail page retains scroll position on the previous list page;
  • When tapped, inputs aren’t obscured by the on-screen keyboard;
  • Content is easily shareable from standalone or full-screen mode;
  • Site is responsive across phone, tablet and desktop screen sizes;
  • Any app install prompts are not used excessively;
  • The Add to Home Screen prompt is intercepted;
  • First load very fast even on 3G;
  • Site uses cache-first networking;
  • Site appropriately informs the user when they’re offline;
  • Provide context to the user about how notifications will be used;
  • UI encouraging users to turn on Push Notifications must not be overly aggressive;
  • Site dims the screen when the permission request is showing;
  • Push notifications must be timely, precise and relevant;
  • Provides controls to enable and disable notifications;
  • User is logged in across devices via Credential Management API;
  • User can pay easily via native UI from Payment Request API.

Crikey! I don’t know about you but that second bunch of stuff seems like a whole lot of work for a basic application! As it happens there are plenty of items there that aren’t relevant to what I had planned anyway. Despite that, I’m not ashamed to say I lowered my sights to only pass the initial tests.

For a whole section of application types, I believe a PWA is a more applicable solution than a native application. Where games and SaaS arguably make more sense in an app store, smaller utilities can live quite happily and more successfully on the web as Progressive Web Applications.

Whilst on the subject of me shirking hard work, another choice made early on was to try and store all data for the application on the users own device. That way it wouldn’t be necessary to hook up with data services and servers and deal with log-ins and authentications. For where my skills were at, figuring out authentication and storing user data seemed like it would almost certainly be biting off more than I could chew and overkill for the remit of the application!

Technology Choices

With a fairly clear idea on what the goal was, attention turned to the tools that could be employed to build it.

I decided early on to use TypeScript, which is described on its website as “… a typed superset of JavaScript that compiles to plain JavaScript.” What I’d seen and read of the language I liked, especially the fact it learned itself so well to static analysis.

Static analysis simply means a program can look at your code before running it (e.g. when it is static) and highlight problems. It can’t necessarily point out logical issues but it can point to non-conforming code against a set of rules.

Anything that could point out my (sure to be many) errors as I went along had to be a good thing, right?

If you are unfamiliar with TypeScript consider the following code in vanilla JavaScript:

console.log(`${count} players`);
let count = 0;

Run this code and you will get an error something like:

ReferenceError: Cannot access uninitialized variable.

For those with even a little JavaScript prowess, for this basic example, they don’t need a tool to tell them things won’t end well.

However, if you write that same code in TypeScript, this happens in the editor:

TypeScript in action

TypeScript in action (Large preview)

I’m getting some feedback on my idiocy before I even run the code! That’s the beauty of static analysis. This feedback was often like having a more experienced developer sat with me catching errors as I went.

TypeScript primarily, as the name implies, let’s you specify the ‘type’ expected for each thing in the code. This prevents you inadvertently ‘coercing’ one type to another. Or attempting to run a method on a piece of data that isn’t applicable — an array method on an object for example. This isn’t the sort of thing that necessarily results in an error when the code runs, but it can certainly introduce hard to track bugs. Thanks to TypeScript you get feedback in the editor before even attempting to run the code.

TypeScript was certainly not essential in this journey of discovery and I would never encourage anyone to jump on tools of this nature unless there was a clear benefit. Setting tools up and configuring tools in the first place can be a time sink so definitely consider their applicability before diving in.

There are other benefits afforded by TypeScript we will come to in the next article in this series but the static analysis capabilities were enough alone for me to want to adopt TypeScript.

There were knock-on considerations of the choices I was making. Opting to build the application as a Progressive Web Application meant I would need to understand Service Workers to some degree. Using TypeScript would mean introducing build tools of some sort. How would I manage those tools? Historically, I’d used NPM as a package manager but what about Yarn? Was it worth using Yarn instead? Being performance-focused would mean considering some minification or bundling tools; tools like webpack were becoming more and more popular and would need evaluating.

Summary

I’d recognized a need to embark on this quest. My JavaScript powers were weak and nothing girds the loins as much as attempting to put theory into practice. Deciding to build a web application with vanilla JavaScript was to be my baptism of fire.

I’d spent some time researching and considering the options for making the application and decided that making the application a Progressive Web App made the most sense for my skill-set and the relative simplicity of the idea.

I’d need build tools, a package manager, and subsequently, a whole lot of patience.

Ultimately, at this point the fundamental question remained: was this something I could actually manage? Or would I be humbled by my own ineptitude?

I hope you join me in part two when you can read about build tools, JavaScript design patterns and how to make something more ‘app-like’.

Smashing Editorial
(dm, yk, il)

Source: Smashing Magazine, Designing And Building A Progressive Web Application Without A Framework (Part 1)

Collective #534

dreamt up by webguru in Uncategorized | Comments Off on Collective #534




C534_flawwwless

Flawwwless

Flawwwless is a coding education platform with easy to follow interactive tutorials.

Check it out



C534_docs

ImportDoc

With ImportDoc you can create a web page that updates dynamically with the content of a Google document.

Check it out



C534_gatsbythemes

Gatsby Themes

Exciting news for Gatsby users: With a Gatsby theme, all of your default configuration (shared functionality, data sourcing, design) is abstracted out of your site, and into an installable package.

Check it out


C534_fwa

The Cool Club FWA

The web presentation of The Cool Club FWA, a deck of cards displaying the 54 coolest websites in history, as featured in “Web Design, The evolution of the Digital World 1990-today”.

Check it out














C534_spreadsheets

Stein

With Stein you can use Google Sheets as your no-setup data store.

Check it out


Collective #534 was written by Pedro Botelho and published on Codrops.


Source: Codrops, Collective #534

The Essential Guide To JavaScript’s Newest Data Type: BigInt

dreamt up by webguru in Uncategorized | Comments Off on The Essential Guide To JavaScript’s Newest Data Type: BigInt

The Essential Guide To JavaScript’s Newest Data Type: BigInt

The Essential Guide To JavaScript’s Newest Data Type: BigInt

Faraz Kelhini



The BigInt data type aims to enable JavaScript programmers to represent integer values larger than the range supported by the Number data type. The ability to represent integers with arbitrary precision is particularly important when performing mathematical operations on large integers. With BigInt, integer overflow will no longer be an issue.

Additionally, you can safely work with high-resolution timestamps, large integer IDs, and more without having to use a workaround. BigInt is currently a stage 3 proposal. Once added to the specification, it will become the second numeric data type in JavaScript, which will bring the total number of supported data types to eight:

  • Boolean
  • Null
  • Undefined
  • Number
  • BigInt
  • String
  • Symbol
  • Object

In this article, we will take a good look at BigInt and see how it can help overcome the limitations of the Number type in JavaScript.

The Problem

The lack of an explicit integer type in JavaScript is often baffling to programmers coming from other languages. Many programming languages support multiple numeric types such as float, double, integer, and bignum, but that’s not the case with JavaScript. In JavaScript, all numbers are represented in double-precision 64-bit floating-point format as defined by the IEEE 754-2008 standard.

Under this standard, very large integers that cannot be exactly represented are automatically rounded. To be precise, the Number type in JavaScript can only safely represent integers between -9007199254740991 (-(253-1)) and 9007199254740991 (253-1). Any integer value that falls out of this range may lose precision.

This can be easily examined by executing the following code:

console.log(9999999999999999);    // → 10000000000000000

This integer is larger than the largest number JavaScript can reliably represent with the Number primitive. Therefore, it’s rounded. Unexpected rounding can compromise a program’s reliability and security. Here’s another example:

// notice the last digits
9007199254740992 === 9007199254740993;    // → true

JavaScript provides the Number.MAX_SAFE_INTEGER constant that allows you to quickly obtain the maximum safe integer in JavaScript. Similarly, you can obtain the minimum safe integer by using the Number.MIN_SAFE_INTEGER constant:

const minInt = Number.MIN_SAFE_INTEGER;

console.log(minInt);         // → -9007199254740991

console.log(minInt - 5);     // → -9007199254740996

// notice how this outputs the same value as above
console.log(minInt - 4);     // → -9007199254740996

The Solution

As a workaround to these limitations, some JavaScript developers represent large integers using the String type. The Twitter API, for example, adds a string version of IDs to objects when responding with JSON. Additionally, a number of libraries such as bignumber.js have been developed to make working with large integers easier.

With BigInt, applications no longer need a workaround or library to safely represent integers beyond Number.MAX_SAFE_INTEGER and Number.Min_SAFE_INTEGER. Arithmetic operations on large integers can now be performed in standard JavaScript without risking loss of precision. The added benefit of using a native data type over a third-party library is better run-time performance.

To create a BigInt, simply append n to the end of an integer. Compare:

console.log(9007199254740995n);    // → 9007199254740995n
console.log(9007199254740995);     // → 9007199254740996

Alternatively, you can call the BigInt() constructor:

BigInt("9007199254740995");    // → 9007199254740995n

BigInt literals can also be written in binary, octal or hexadecimal notation:


// binary
console.log(0b100000000000000000000000000000000000000000000000000011n);
// → 9007199254740995n

// hex
console.log(0x20000000000003n);
// → 9007199254740995n

// octal
console.log(0o400000000000000003n);
// → 9007199254740995n

// note that legacy octal syntax is not supported
console.log(0400000000000000003n);
// → SyntaxError

Keep in mind that you can’t use the strict equality operator to compare a BigInt to a regular number because they are not of the same type:

console.log(10n === 10);    // → false

console.log(typeof 10n);    // → bigint
console.log(typeof 10);     // → number

Instead, you can use the equality operator, which performs implicit type conversion before compering its operands:

console.log(10n == 10);    // → true

All arithmetic operators can be used on BigInts except for the unary plus (+) operator:

10n + 20n;    // → 30n
10n - 20n;    // → -10n
+10n;         // → TypeError: Cannot convert a BigInt value to a number
-10n;         // → -10n
10n * 20n;    // → 200n
20n / 10n;    // → 2n
23n % 10n;    // → 3n
10n ** 3n;    // → 1000n

const x = 10n;
++x;          // → 11n
--x;          // → 9n

The reason that the unary plus (+) operator is not supported is that some programs may rely on the invariant that + always produces a Number, or throws an exception. Changing the behavior of + would also break asm.js code.

Naturally, when used with BigInt operands, arithmetic operators are expected to return a BigInt value. Therefore, the result of the division (/) operator is automatically rounded down to the nearest integer. For example:

25 / 10;      // → 2.5
25n / 10n;    // → 2n

Implicit Type Conversion

Because implicit type conversion could lose information, mixed operations between BigInts and Numbers are not allowed. When mixing large integers and floating-point numbers, the resulting value may not be accurately representable by BigInt or Number. Consider the following example:

(9007199254740992n + 1n) + 0.5

The result of this expression is outside of the domain of both BigInt and Number. A Number with a fractional part cannot be accurately converted to a BigInt. And a BigInt larger than 253 cannot be accurately converted to a Number.

As a result of this restriction, it’s not possible to perform arithmetic operations with a mix of Number and BigInt operands. You also cannot pass a BigInt to Web APIs and built-in JavaScript functions that expect a Number. Attempting to do so will cause a TypeError:

10 + 10n;    // → TypeError
Math.max(2n, 4n, 6n);    // → TypeError

Note that relational operators do not follow this rule, as shown in this example:

10n > 5;    // → true

If you want to perform arithmetic computations with BigInt and Number, you first need to determine the domain in which the operation should be done. To do that, simply convert either of the operands by calling Number() or BigInt():

BigInt(10) + 10n;    // → 20n
// or
10 + Number(10n);    // → 20

When encountered in a Boolean context, BigInt is treated similar to Number. In other words, a BigInt is considered a truthy value as long as it’s not 0n:

if (5n) {
    // this code block will be executed
}

if (0n) {
    // but this code block won't
}

No implicit type conversion occurs when sorting an array of BigInts and Numbers:

const arr = [3n, 4, 2, 1n, 0, -1n];

arr.sort();    // → [-1n, 0, 1n, 2, 3n, 4]

Bitwise operators such as |, &, <<, >>, and ^ operate on BigInts in a similar way to Numbers. Negative numbers are interpreted as infinite-length two’s complement. Mixed operands are not allowed. Here are some examples:

90 | 115;      // → 123
90n | 115n;    // → 123n
90n | 115;     // → TypeError

The BigInt Constructor

As with other primitive types, a BigInt can be created using a constructor function. The argument passed to BigInt() is automatically converted to a BigInt, if possible:

BigInt("10");    // → 10n
BigInt(10);      // → 10n
BigInt(true);    // → 1n

Data types and values that cannot be converted throw an exception:

BigInt(10.2);     // → RangeError
BigInt(null);     // → TypeError
BigInt("abc");    // → SyntaxError

You can directly perform arithmetic operations on a BigInt created using a constructor:

BigInt(10) * 10n;    // → 100n

When used as operands of the strict equality operator, BigInts created using a constructor are treated similar to regular ones:

BigInt(true) === 1n;    // → true

Library Functions

JavaScript provides two library functions for representing BigInt values as signed or unsigned integers:

  • BigInt.asUintN(width, BigInt): wraps a BigInt between 0 and 2width-1
  • BigInt.asIntN(width, BigInt): wraps a BigInt between -2width-1 and 2width-1-1

These functions are particularly useful when performing 64-bit arithmetic operations. This way you can stay within the intended range.

Browser Support And Transpiling

At the time of this writing, Chrome +67 and Opera +54 fully support the BigInt data type. Unfortunately, Edge and Safari haven’t implemented it yet. Firefox doesn’t support BigInt by default, but it can be enabled by setting javascript.options.bigint to true in about:config. An up-to-date list of supported browsers is available on Can I use….

Unluckily, transpiling BigInt is an extremely complicated process, which incurs hefty run-time performance penalty. It’s also impossible to directly polyfill BigInt because the proposal changes the behavior of several existing operators. For now, a better alternative is to use the JSBI library, which is a pure-JavaScript implementation of the BigInt proposal.

This library provides an API that behaves exactly the same as the native BigInt. Here’s how you can use JSBI:

import JSBI from './jsbi.mjs';

const b1 = JSBI.BigInt(Number.MAX_SAFE_INTEGER);
const b2 = JSBI.BigInt('10');

const result = JSBI.add(b1, b2);

console.log(String(result));    // → '9007199254741001'

An advantage of using JSBI is that once browser support improves, you won’t need to rewrite your code. Instead, you can automatically compile your JSBI code into native BigInt code by using a babel plugin. Furthermore, the performance of JSBI is on par with native BigInt implementations. You can expect wider browser support for BigInt soon.

Conclusion

BigInt is a new data type intended for use when integer values are larger than the range supported by the Number data type. This data type allows us to safely perform arithmetic operations on large integers, represent high-resolution timestamps, use large integer IDs, and more without the need to use a library.

It’s important to keep in mind that you cannot perform arithmetic operations with a mix of Number and BigInt operands. You’ll need to determine the domain in which the operation should be done by explicitly converting either of the operands. Moreover, for compatibility reasons, you are not allowed to use the unary plus (+) operator on a BigInt.

What do you think? Do you find BigInt useful? Let us know in the comments!

Smashing Editorial
(dm, yk, il)

Source: Smashing Magazine, The Essential Guide To JavaScript’s Newest Data Type: BigInt

Monthly Web Development Update 7/2019: Modern Techniques And Good Trouble

dreamt up by webguru in Uncategorized | Comments Off on Monthly Web Development Update 7/2019: Modern Techniques And Good Trouble

Monthly Web Development Update 7/2019: Modern Techniques And Good Trouble

Monthly Web Development Update 7/2019: Modern Techniques And Good Trouble

Anselm Hannemann



What can we do to cause “good trouble”? First of all, I think it needs to be friendly, helpful and meaningful actions that don’t impact other peoples’ lives. Secondly, it’s something we strongly believe in — it might be using simpler JavaScript methods, reducing the application size, a better toggle UI, publishing a book or building a business without selling user data to others. Whatever it is, it’s good to have a standpoint of view and talk about it.

It’s good to advocate others about accessibility problems, about how to listen better to others in a conversation, how to manage projects, products or even a company better. The most important thing on all these actions is to remember that they are helping other people and not impacting them as well as animals or our environment in general.

Doing something useful — as small as it might seem — is always a good thing. And don’t forget to honor your action just by smiling and being thankful for what you did!

News

  • Chrome 76 removes a couple of things like feature policy: lazyload, insecure usage of DeviceMotionEvent and the DeviceOrientationEvent. If you use them, please ensure you use a secure context by now or replace them by their successors.
  • Firefox 68 is out and this is new: BigInts for JavaScript, Accessibility Checks in DevTools, CSS Scroll Snapping and Marker Styling, access to cameras, microphones, and other media devices is no longer allowed in insecure contexts like plain HTTP. It’s now possible to resend a network request without editing the method, URL, parameters, and headers via DevTools, and a lot of (compatibility) fixes are included for CSS features as well.
  • Chrome 76 brings image support for the async clipboard API, making it easy to programmatically copy and paste image/png (currently, this is the only supported format though, unfortunately) images.
  • Tracking prevention is now available in Microsoft Edge preview, following other browsers like Safari and Firefox.

Generic

  • Have you heard of the concept of “good trouble”? Frank Chimero defines it as questioning and re-imagining the status quo, and having your actions stand in contrast to the norm. But the interview with the designer shows much more than a new concept, it’s challenging how we work today and how to do your own thing that doesn’t match the norm of the society.

Particularly, I like this quote here:

“Slow down, find a quiet place and create time for solitude so you can hear yourself. It’s so noisy out there.”

  • What if control is only an illusion? We would realize that the true nature of an experience is revealed only in the interplay with the people who use it and that an invalidated design is nothing but an opinion. Quite a thought that puts our assumptions and approach on projects into a different light.

UI/UX

Accessibility

JavaScript

CSS

Work & Life

  • Active Listening is a skill that helps us listening for meaning, and how the other person is feeling instead of that usual listening that focuses on ‘how can I reply or comment on this or how will we solve this?’. Buffer’s guide written by Marcus Wermuth is a great resource to learn and practice Active Listening.
  • Christoph Rumpel shares what he learned from self-publishing a book and shows interesting insights into finances of it and what to avoid or do better.
  • Ben Werdmüller on doing well while doing good: This is a personal story about struggling with revenue, investments, third-party capital, trying to earn money on your own by selling your product while having free competitors and how to still produce good things while doing financially well.
  • Shape Up — Stop Running in Circles and Ship Work that Matters is a new, free online book by Ryan Singer about project management, leading a company and product. It’s amazing and while I only had time to flick through it quickly and read some individual chapters and sections, this will definitely become a resource to save and refer to regularly.

Going Beyond…

I was in the cinema last week to watch a movie about some people who created a farm. The trailer was nice and while I wasn’t 100% convinced of it, it was an evening where I was up to go out to watch a movie. So I did and it was good that I went to see “The Biggest Little Farm”. The farmer made the film himself as he’s a wildlife filmmaker so expect some quite stunning pictures and sequences of wildlife animals in there!

The most revealing part was how much of an impact only a handful of people can make out of desert land in a few years of time, and how much we as humans can influence wildlife, give a habitat to insects, and produce quality food while including CO2 from the air into our soil to make plants grow better, in order to restore nature and make an impact in the effort to fight climate change.

At several points during the movie, I was close to tears and I was extremely thankful that I’m able to have my little garden space as well where I can do similar things (though way smaller than their farm). If you’re up for something new, to learn something about food, meat, economy and how it all connects or how to create a beautiful green space out of desert, this movie is for you.

Last but not least, solar panels are a good way to produce renewable energy and it’s good usage of roofs. In China though, air pollution is currently so bad that solar panels sometimes stop working. Another reason to act quickly! If solar panels don’t work due to missing sunrays, our bodies will suffer the same lack of sunlight and we need it for our health.

Smashing Editorial
(il)

Source: Smashing Magazine, Monthly Web Development Update 7/2019: Modern Techniques And Good Trouble

Collective #533

dreamt up by webguru in Uncategorized | Comments Off on Collective #533




C533_isntallation

Thorne: The Frontier Within

A case study of the wonderful The Frontier Within which is an immersive installation and web experience that captures the participant’s circulatory, respiratory and nervous system data, and transforms it into a living, breathing, interactive portrait of the body.

Read it


C533_reducemotion

Reduced Motion Auto-Play Video

Scott O’Hara shows how to use the reduced motion media query to implement video components in a way that will respect user preferences from an OS level.

Read it


C533_slow

Is postMessage slow?

An article by Surma that investigates the performance of postMessage() and how to avoid blowing your budgets.

Read it




C533_repolovers

Repo Lovers

An online magazine made for developers, coders, hackers, makers, tinkers and everything else in between. Repo Lovers sets out to build an archive of interviews featuring talented folks building software.

Check it out













C533_uichat

Chat Messaging UI Kit

A high fidelity Chat UI kit for Sketch. Chat interfaces for live chat, team collaboration, messaging, customer support and gaming are included.

Get it



Collective #533 was written by Pedro Botelho and published on Codrops.


Source: Codrops, Collective #533

Yarn Workspaces: Organize Your Project’s Codebase Like A Pro

dreamt up by webguru in Uncategorized | Comments Off on Yarn Workspaces: Organize Your Project’s Codebase Like A Pro

Yarn Workspaces: Organize Your Project’s Codebase Like A Pro

Yarn Workspaces: Organize Your Project’s Codebase Like A Pro

Jorge Ferreiro



Any time I start working on a new project, I ask myself, “Should I use separate git repositories for my back-end server and my front-end client(s)? What’s the best way to organize the codebase?”

I had this same question after a few months working on my personal website. I originally had all the code in the same repository: the back end used Node.js and the front end used ES6 with Pug. I adopted this organization for convenience, since having both projects in the same repo made it easy to search for functions and classes, and facilitated refactors. However, I found some downsides:

  • No independent deployments.
    Both apps were using the same package.json, and there was no clear separation on both projects.
  • Unclear boundaries.
    Since I rely on a global package.json, I didn’t have a mechanism to set specific versions for the back end and front end.
  • Shared utilities and code without versioning.

After some research, I found that Yarn workspaces was a great tool to solve those cons, and it was a helpful tool to create a monorepo project (more to come later!).

In this article, I share an intro to Yarn workspaces. We’ll run through a tutorial together on how to create your first project with it, and we’ll finish with a recap and next steps.

What Are Yarn Workspaces?

Yarn is a package manager by the folks at Facebook, and it has a great feature called Yarn workspaces. Yarn workspaces let you organize your project codebase using a monolithic repository (monorepo). The idea is that a single repository would contain multiple packages. Packages are isolated and could live independent of the larger project.

Yarn Workspaces

As an alternative, we could place all of these packages into separate repositories. Unfortunately, this approach affects the shareability, efficiency, and developer experience when developing on the packages and their dependent projects. Furthermore, when we work in a single repository we can move more swiftly and build more specific tooling to improve processes for the entire development life cycle.


Monorepo projects have been widely accepted by large companies like Google or Facebook, and they have proven monorepo can scale.

React is a good example of an open-source project that is monorepo. Also, React uses Yarn workspaces to achieve that purpose. In the next section we will learn how to create our first monorepo project with Yarn.

Creating A Monorepo Project With React And Express Using Yarn Workspaces In Six Steps

So far, we have learned what Yarn is, what a monorepo is, and why Yarn is a great tool to create a monorepo. Now let’s learn from scratch how to set up a new project using Yarn workspaces. To follow along, you’ll need a working environment with an up-to-date npm install. Download the source code.

Prerequisites

To fully complete this tutorial, you will need to have Yarn installed on your machine. If you haven’t installed Yarn before, please follow these instructions.

These are the steps we’ll be following in this tutorial:

  1. Create Your Project And Root Workspace
  2. Create A React Project And Add It To The Workspace List
  3. Create An Express Project And Add It To The Workspace
  4. Install All The Dependencies And Say Hello To yarn.lock
  5. Using A Wildcard (*) To Import All Your Packages
  6. Add A Script To Run Both Packages

1. Create Your Project And Root Workspace

In your local machine terminal, create a new folder called example-monorepo:

$ mkdir example-monorepo

Inside the folder, create a new package.json with our root workspace.

$ cd example-monorepo
$ touch package.json

This package should be private in order to prevent accidentally publishing the root workspace. Add the following code to your new package.json file to make the package private:

{
   "private": true,
   "name": "example-monorepo",
   "workspaces": [],
   "scripts": {}
}

2. Create A React Project And Add It To The Workspace List

In this step, we will create a new React project and add it to the list of packages inside the root workspace.

First, let’s create a folder called packages where we will add the different projects we will create in the tutorial:

$ mkdir packages

Facebook has a command to create new React projects: create-react-app. We’ll use it to create a new React app with all the required configuration and scripts. We are creating this new project with the name “client” inside the packages folder that we created in step 1.

$ yarn create react-app packages/client

Once we have created our new React project, we need to tell Yarn to treat that project as a workspace. To do that, we simply need to add “client” (the name we used earlier) inside the “workspaces” list in the root package.json. Be sure to use the same name you used when running the create-react-app command.

{
   "private": true,
   "name": "example-monorepo",
   "workspaces": ["client"],
   "scripts": {}
}

3. Create An Express Project And Add It To The Workspace

Now it’s time to add a back-end app! We use express-generator to create an Express skeleton with all the required configuration and scripts.

Make sure you have express-generator installed on your computer. You can install it using Yarn with the following command:

$ yarn global add express-generator --prefix /usr/local

Using express-generator, we create a new Express app with the name “server” inside the packages folder.

$ express --view=pug packages/server

Finally, add the new package “server” into the workspaces list inside the root package.json.

{
   "private": true,
   "name": "example-monorepo",
   "workspaces": ["client", "server"],
   "scripts": {}
}

Note: This tutorial is simplified with only two packages (server and client). In a project, you might typically have as many packages as you need, and by convention the open-source community use this naming pattern: @your-project-name/package-name. For example: I use @ferreiro/server on my website.

4. Install All The Dependencies And Say Hello To yarn.lock

Once we have added our React app, as well as our Express server, we need to install all the dependencies. Yarn workspaces simplifies this process and we no longer need to go to every single application and install their dependencies manually. Instead, we execute one command — yarn install — and Yarn does the magic to install all the dependencies for every package, and optimize and cache them.

Run the following command:

$ yarn install

This command generates a yarn.lock file (similar to this example). It contains all the dependencies for your project, as well as the version numbers for each dependency. Yarn generates this file automatically, and you should not modify it.

5. Using A Wildcard (*) To Import All Your Packages

Until now, for every new package we have added, we were forced to also update the root package.json to include the new package to the workspaces:[] list.

We can avoid this manual step using a wildcard (*) that tells Yarn to include all the packages inside the packages folder.

Inside the root package.json, update the file content with the following line: "workspaces": ["packages/*"]

{
   "private": true,
   "name": "example-monorepo",
   "workspaces": ["packages/*"],
   "scripts": {}
}

6. Add A Script To Run Both Packages

Last step! We need to have a way to run both packages — the React client and the Express client — simultaneously. For this example, we will use concurrently. This package let us run multiple commands in parallel.

Add concurrently to the root package.json:

$ yarn add -W concurrently

Add three new scripts inside the root workspace package.json. Two scripts initialize the React and Express clients independently; the other one uses concurrently to run both scripts in parallel. See this code for reference.

{
   "private": true,
   "name": "example-monorepo",
   "workspaces": ["packages/*"],
   "scripts": {
       "client": "yarn workspace client start",
       "server": "yarn workspace server start",
       "start": "concurrently --kill-others-on-fail "yarn server"  "yarn client"
   }
}

Note: We will not need to write our start scripts into the “server” and “client” packages because the tools we used to generate those packages (create-react-app and express-generator) already add those scripts for us. So we are good to go!

Finally, make sure you update the Express boot-up script to run the Express server on port 4000. Otherwise, the client and server will try to use the same port (3000).

Go to packages/server/bin/www and change the default port in line 15.

var port = normalizePort(process.env.PORT || '4000');

Now we are ready to run our packages!

$ yarn start

Where To Go From Here

Let’s recap what we’ve covered. First, we learned about Yarn workspaces and why it’s a great tool to create a monorepo project. Then, we created our first JavaScript monorepo project using Yarn, and we divided the logic of our app into multiple packages: client and server. Also, we created our first basic npm scripts and added the required dependencies for each app.

From this point, I’d suggest you review open-source projects in detail to see how they use Yarn workspaces to split the project logic into many packages. React is a good one.

Jorge Ferreiro’s website using yarn workspaces and packages with a back-end and frontend apps

Jorge Ferreiro’s website using yarn workspaces and packages with a back-end and frontend apps (Large preview)

Also, if you want to see a production website using this approach to separate back-end and front-end apps into independent packages, you can check the source of my website, that also includes a blog admin. When I migrated the codebase to use Yarn workspaces, I created a pull request with Kyle Wetch.

Moreover, I set up the infrastructure for a hackathon project that uses React, webpack, Node.js, and Yarn workspaces, and you can check the source code over here.

Finally, it would be really interesting for you to learn how to publish your independent packages to become familiar with the development life cycle. There are a couple of tutorials that are interesting to check: yarn publish or npm publish.

For any comments or questions, don’t hesitate to reach out to me on Twitter. Also, in the following months, I’ll publish more content about this in my blog, so you can subscribe there as well. Happy coding!

Smashing Editorial
(dm, og, il)

Source: Smashing Magazine, Yarn Workspaces: Organize Your Project’s Codebase Like A Pro