SitePoint

SitePoint

Description

Learn CSS | HTML5 | JavaScript | Wordpress | Tutorials-Web Development | Reference | Books and More

Link: www.sitepoint.com

Episodes

Getting Started with Puppeteer

Nov 14, 2019

Description:

Getting Started with Puppeteer

Browser developer tools provide an amazing array of options for delving under the hood of websites and web apps. These capabilities can be further enhanced and automated by third-party tools. In this article, we'll look at Puppeteer, a Node-based library for use with Chrome/Chromium.

The puppeteer website describes Puppeteer as

a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.

Puppeteer is made by the team behind Google Chrome, so you can be pretty sure it will be well maintained. It lets us perform common actions on the Chromium browser, programmatically through JavaScript, via a simple and easy-to-use API.

With Puppeteer, you can:

scrape websites generate screenshots of websites including SVG and Canvas create PDFs of websites crawl an SPA (single-page application) access web pages and extract information using the standard DOM API generate pre-rendered content — that is, server-side rendering automate form submission automate performance analysis automate UI testing like Cypress test chrome extensions

Puppeteer does nothing new that Selenium, PhantomJS (which is now deprecated), and the like do, but it provides a simple and easy-to-use API and provides a great abstraction so we don't have to worry about the nitty-gritty details when dealing with it.

It's also actively maintained so we get all the new features of ECMAScript as Chromium supports it.

Prerequisites

For this tutorial, you need a basic knowledge of JavaScript, ES6+ and Node.js.

You must also have installed the latest version of Node.js.

We’ll be using yarn throughout this tutorial. If you don’t have yarn already installed, install it from here.

To make sure we’re on the same page, these are the versions used in this tutorial:

Node 12.12.0 yarn 1.19.1 puppeteer 2.0.0 Installation

To use Puppeteer in your project, run the following command in the terminal:

$ yarn add puppeteer

Note: when you install Puppeteer, it downloads a recent version of Chromium (~170MB macOS, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API. To skip the download, see Environment variables.

If you don't need to download Chromium, then you can install puppeteer-core:

$ yarn add puppeteer-core

puppeteer-core is intended to be a lightweight version of Puppeteer for launching an existing browser installation or for connecting to a remote one. Be sure that the version of puppeteer-core you install is compatible with the browser you intend to connect to.

Note: puppeteer-core is only published from version 1.7.0.

Usage

Puppeteer requires at least Node v6.4.0, but we're going to use async/await, which is only supported in Node v7.6.0 or greater, so make sure to update your Node.js to the latest version to get all the goodies.

Let's dive into some practical examples using Puppeteer. In this tutorial, we'll be:

generating a screenshot of Unsplash using Puppeteer creating a PDF of Hacker News using Puppeteer signing in to Facebook using Puppeteer 1. Generate a Screenshot of Unsplash using Puppeteer

It's really easy to do this with Puppeteer. Go ahead and create a screenshot.js file in the root of your project. Then paste in the following code:

const puppeteer = require('puppeteer') const main = async () => { const browser = await puppeteer.launch() const page = await browser.newPage() await page.goto('https://unsplash.com') await page.screenshot({ path: 'unsplash.png' }) await browser.close() } main()

Firstly, we require the puppeteer package. Then we call the launch method on it that initializes the instance. This method is asynchronous as it returns a Promise. So we await for it to get the browser instance.

Then we call newPage on it and go to Unsplash and take a screenshot of it and save the screenshot as unsplash.png.

Now go ahead and run the above code in the terminal by typing:

$ node screenshot

Unsplash - 800px x 600px resolution

Now after 5–10 seconds you'll see an unsplash.png file in your project that contains the screenshot of Unsplash. Notice that the viewport is set to 800px x 600px as Puppeteer sets this as the initial page size, which defines the screenshot size. The page size can be customized with Page.setViewport().

Let's change the viewport to be 1920px x 1080px. Insert the following code before the goto method:

await page.setViewport({ width: 1920, height: 1080, deviceScaleFactor: 1, })

Now go ahead and also change the filename from unsplash.png to unsplash2.png in the screenshot method like so:

await page.screenshot({ path: 'unsplash2.png' })

The whole screenshot.js file should now look like this:

const puppeteer = require('puppeteer') const main = async () => { const browser = await puppeteer.launch() const page = await browser.newPage() await page.setViewport({ width: 1920, height: 1080, deviceScaleFactor: 1, }) await page.goto('https://unsplash.com') await page.screenshot({ path: 'unsplash2.png' }) await browser.close() } main()

Unsplash - 1920px x 1080px

The post Getting Started with Puppeteer appeared first on SitePoint.

Getting Started with the React Native Navigation Library

Nov 13, 2019

Description:

Getting Started with the React Native Navigation Library

One of the most important aspects of React Native app development is the navigation. It’s what allows users to get to the pages they’re looking for. That’s why it’s important to choose the best navigation library to suit your needs.

If your app has a lot of screens with relatively complex UI, it might be worth exploring React Native Navigation instead of React Navigation. This is because there will always be performance bottlenecks with React Navigation, since it works off the same JavaScript thread as the rest of the app. The more complex your UI, the more data has to be passed to that bridge, which can potentially slow it down.

In this tutorial, we’ll be looking at the React Native Navigation library by Wix, an alternative navigation library for those who are looking for a smoother navigation performance for their React Native apps.

Prerequisites

Knowledge of React and React Native is required to follow this tutorial. Prior experience with a navigation library such as React Navigation is optional.

App Overview

In order to demonstrate how to use the library, we’ll be creating a simple app that uses it. The app will have five screens in total:

Initialization: this serves as the initial screen for the app. If the user is logged in, it will automatically navigate to the home screen. If not, the user is navigated to the login screen. Login: this allows the user to log in so they can view the home, gallery, and feed. To simplify things, the login will just be mocked; no actual authentication code will be involved. From this screen, the user can also go to the forgot-password screen. ForgotPassword: a filler screen, which asks for the user’s email address. This will simply be used to demonstrate stack navigation. Home: the initial screen that the user will see when they log in. From here, they can also navigate to either the gallery or feed screens via a bottom tab navigation. Gallery: a filler screen which shows a photo gallery UI. Feed: a filler screen which shows a news feed UI.

Here’s what the app will look like:

React Native Navigation demo gif

You can find the source code of the sample app on this GitHub repo.

Bootstrapping the App

Let’s start by generating a new React Native project:

react-native init RNNavigation --version react-native@0.57.8

Note: we’re using a slightly older version of React Native, because React Native Navigation doesn’t work well with later versions of React Native. React Native Navigation hasn’t really kept up with the changes in the core of React Native since version 0.58. The only version known to work flawlessly with React Native is the version we’re going to use. If you check the issues on their repo, you’ll see various issues on version 0.58 and 0.59. There might be workarounds on those two versions, but the safest bet is still version 0.57.

As for React Native version 0.60, the core team has made a lot of changes. One of them is the migration to AndroidX, which aims to make it clearer which packages are bundled with the Android operating system. This essentially means that if a native module uses any of the old packages that got migrated to the new androidx.* package hierarchy, it will break. There are tools such as jetifier, which allows for migration to AndroidX. But this doesn’t ensure React Native Navigation will work.

Next, install the dependencies of the app:

react-native-navigation — the navigation library that we’re going to use. @react-native-community/async-storage — for saving data to the app’s local storage. react-native-vector-icons — for showing icons for the bottom tab navigation. yarn add react-native-navigation @react-native-community/async-storage react-native-vector-icons

In the next few sections, we’ll be setting up the packages we just installed.

Setting up React Native Navigation

First, we’ll set up the React Native Navigation library. The instructions that we’ll be covering here are also in the official documentation. Unfortunately, it’s not written in a very friendly way for beginners, so we’ll be covering it in more detail.

Note: the demo project includes an Android and iOS folders as well. You can use those as a reference if you encounter any issues with setting things up.

Since the name of the library is very long, I’ll simply refer to it as RNN from now on.

Android Setup

In this section, we’ll take a look at how you can set up RNN for Android. Before you proceed, it’s important to update all the SDK packages to the latest versions. You can do that via the Android SDK Manager.

settings.gradle

Add the following to your android/settings.gradle file:

include ':react-native-navigation' project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/lib/android/app/') Gradle Wrapper Properties

In your android/gradle/wrapper/gradle-wrapper.properties, update Gradle’s distributionUrl to use version 4.4 if it’s not already using it:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip build.gradle

Next, in your android/build.gradle file, add mavenLocal() and mavenCentral() under buildscript -> repositories:

buildscript { repositories { google() jcenter() // add these: mavenLocal() mavenCentral() } }

Next, update the classpath under the buildscript -> dependencies to point out to the Gradle version that we need:

buildscript { repositories { ... } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' } }

Under allprojects -> repositories, add mavenCentral() and JitPack. This allows us to pull the data from React Native Navigation’s JitPack repository:

allprojects { allprojects { repositories { mavenLocal() google() jcenter() mavenCentral() // add this maven { url 'https://jitpack.io' } // add this } }

Next, add the global config for setting the build tools and SDK versions for Android:

allprojects { ... } ext { buildToolsVersion = "27.0.3" minSdkVersion = 19 compileSdkVersion = 26 targetSdkVersion = 26 supportLibVersion = "26.1.0" }

Lastly, we’d still want to keep the default react-native run-android command when compiling the app, so we have to set Gradle to ignore other flavors of React Native Navigation except the one we’re currently using (reactNative57_5). Ignoring them ensures that we only compile the specific version we’re depending on:

ext { ... } subprojects { subproject -> afterEvaluate { if ((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) { android { variantFilter { variant -> def names = variant.flavors*.name if (names.contains("reactNative51") || names.contains("reactNative55") || names.contains("reactNative56") || names.contains("reactNative57")) { setIgnore(true) } } } } } }

Note: there are four other flavors of RNN that currently exist. These are the ones we’re ignoring above:

reactNative51 reactNative55 reactNative56 reactNative57 android/app/build.gradle

On your android/app/build.gradle file, under android -> compileOptions, make sure that the source and target compatibility version is 1.8:

android { defaultConfig { ... } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } }

Then, in your dependencies, include react-native-navigation as a dependency:

dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}" implementation "com.facebook.react:react-native:+" implementation project(':react-native-navigation') // add this }

Lastly, under android -> defaultConfig, set the missingDimensionStrategy to reactNative57_5. This is the version of RNN that’s compatible with React Native 0.57.8:

defaultConfig { applicationId "com.rnnavigation" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion missingDimensionStrategy "RNN.reactNativeVersion", "reactNative57_5" // add this versionCode 1 versionName "1.0" ndk { abiFilters "armeabi-v7a", "x86" } }

The post Getting Started with the React Native Navigation Library appeared first on SitePoint.

How TypeScript Makes You a Better JavaScript Developer

Nov 12, 2019

Description:

TypeScript

What do Airbnb, Google, Lyft and Asana have in common? They've all migrated several codebases to TypeScript.

Whether it is eating healthier, exercising, or sleeping more, our humans love self-improvement. The same applies to our careers. If someone shared tips for improving as a programmer, your ears would perk.

In this article, the goal is to be that someone. We know TypeScript will make you a better JavaScript developer for several reasons. You'll feel confident when writing code. Fewer errors will appear in your production code. It will be easier to refactor code. You'll write fewer tests (yay!). And overall, you'll have a better coding experience in your editor.

What Even Is TypeScript?

TypeScript is a compiled language. You write TypeScript and it compiles to JavaScript. Essentially, you're writing JavaScript, but with a type system. JavaScript developers should have a seamless transition because the languages are the same, except for a few quirks.

Here's a basic example of a function in both JavaScript and TypeScript:

function helloFromSitePoint(name) { return `Hello, ${name} from SitePoint!` } function helloFromSitePoint(name: string) { return `Hello, ${name} from SitePoint!` }

Notice how the two are almost identical. The difference is the type annotation on the "name" parameter in TypeScript. This tells the compiler, "Hey, make sure when someone calls this function, they only pass in a string." We won't go into much depth but this example should illustrate the bare minimal of TypeScript.

How Will TypeScript Make Me Better?

TypeScript will improve your skills as a JavaScript developer by:

giving you more confidence, catching errors before they hit production, making it easier to refactor code, saving you time from writing tests, providing you with a better coding experience.

Let's explore each of these a bit deeper.

The post How TypeScript Makes You a Better JavaScript Developer appeared first on SitePoint.

Face Detection and Recognition with Keras

Nov 7, 2019

Description:

Face Detection and Recognition with Keras

If you're a regular user of Google Photos, you may have noticed how the application automatically extracts and groups faces of people from the photos that you back up to the cloud.

Face Recognition in the Google Photos web applicationFace Recognition in the Google Photos web application

A photo application such as Google's achieves this through the detection of faces of humans (and pets too!) in your photos and by then grouping similar faces together. Detection and then classification of faces in images is a common task in deep learning with neural networks.

In the first step of this tutorial, we'll use a pre-trained MTCNN model in Keras to detect faces in images. Once we've extracted the faces from an image, we'll compute a similarity score between these faces to find if they belong to the same person.

Prerequisites

Before you start with detecting and recognizing faces, you need to set up your development environment. First, you need to "read" images through Python before doing any processing on them. We'll use the plotting library matplotlib to read and manipulate images. Install the latest version through the installer pip:

pip3 install matplotlib

To use any implementation of a CNN algorithm, you need to install keras. Download and install the latest version using the command below:

pip3 install keras

The algorithm that we'll use for face detection is MTCNN (Multi-Task Convoluted Neural Networks), based on the paper Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks (Zhang et al., 2016). An implementation of the MTCNN algorithm for TensorFlow in Python3.4 is available as a package. Run the following command to install the package through pip:

pip3 install mtcnn

To compare faces after extracting them from images, we'll use the VGGFace2 algorithm developed by the Visual Geometry Group at the University of Oxford. A TensorFlow-based Keras implementation of the VGG algorithm is available as a package for you to install:

pip3 install keras_vggface

While you may feel the need to build and train your own model, you'd need a huge training dataset and vast processing power. Since this tutorial focuses on the utility of these models, it uses existing, trained models by experts in the field.

Now that you've successfully installed the prerequisites, let's jump right into the tutorial!

Step 1: Face Detection with the MTCNN Model

The objectives in this step are as follows:

retrieve images hosted externally to a local server read images through matplotlib's imread() function detect and explore faces through the MTCNN algorithm extract faces from an image. 1.1 Store External Images

You may often be doing an analysis from images hosted on external servers. For this example, we'll use two images of Lee Iacocca, the father of the Mustang, hosted on the BBC and The Detroit News sites.

To temporarily store the images locally for our analysis, we'll retrieve each from its URL and write it to a local file. Let's define a function store_image for this purpose:

import urllib.request def store_image(url, local_file_name): with urllib.request.urlopen(url) as resource: with open(local_file_name, 'wb') as f: f.write(resource.read())

You can now simply call the function with the URL and the local file in which you'd like to store the image:

store_image('https://ichef.bbci.co.uk/news/320/cpsprodpb/5944/production/_107725822_55fd57ad-c509-4335-a7d2-bcc86e32be72.jpg', 'iacocca_1.jpg') store_image('https://www.gannett-cdn.com/presto/2019/07/03/PDTN/205798e7-9555-4245-99e1-fd300c50ce85-AP_080910055617.jpg?width=540&height=&fit=bounds&auto=webp', 'iacocca_2.jpg')

After successfully retrieving the images, let's detect faces in them.

1.2 Detect Faces in an Image

For this purpose, we'll make two imports — matplotlib for reading images, and mtcnn for detecting faces within the images:

from matplotlib import pyplot as plt from mtcnn.mtcnn import MTCNN

Use the imread() function to read an image:

image = plt.imread('iacocca_1.jpg')

Next, initialize an MTCNN() object into the detector variable and use the .detect_faces() method to detect the faces in an image. Let's see what it returns:

detector = MTCNN() faces = detector.detect_faces(image) for face in faces: print(face)

For every face, a Python dictionary is returned, which contains three keys. The box key contains the boundary of the face within the image. It has four values: x- and y- coordinates of the top left vertex, width, and height of the rectangle containing the face. The other keys are confidence and keypoints. The keypoints key contains a dictionary containing the features of a face that were detected, along with their coordinates:

{'box': [160, 40, 35, 44], 'confidence': 0.9999798536300659, 'keypoints': {'left_eye': (172, 57), 'right_eye': (188, 57), 'nose': (182, 64), 'mouth_left': (173, 73), 'mouth_right': (187, 73)}} 1.3 Highlight Faces in an Image

Now that we've successfully detected a face, let's draw a rectangle over it to highlight the face within the image to verify if the detection was correct.

To draw a rectangle, import the Rectangle object from matplotlib.patches:

from matplotlib.patches import Rectangle

Let's define a function highlight_faces to first display the image and then draw rectangles over faces that were detected. First, read the image through imread() and plot it through imshow(). For each face that was detected, draw a rectangle using the Rectangle() class.

Finally, display the image and the rectangles using the .show() method. If you're using Jupyter notebooks, you may use the %matplotlib inline magic command to show plots inline:

def highlight_faces(image_path, faces): # display image image = plt.imread(image_path) plt.imshow(image) ax = plt.gca() # for each face, draw a rectangle based on coordinates for face in faces: x, y, width, height = face['box'] face_border = Rectangle((x, y), width, height, fill=False, color='red') ax.add_patch(face_border) plt.show()

Let's now display the image and the detected face using the highlight_faces() function:

highlight_faces('iacocca_1.jpg', faces) Detected face in an image of Lee IacoccaDetected face in an image of Lee Iacocca. Source: BBC

Let's display the second image and the face(s) detected in it:

image = plt.imread('iacocca_2.jpg') faces = detector.detect_faces(image) highlight_faces('iacocca_2.jpg', faces) The Detroit NewsThe Detroit News

In these two images, you can see that the MTCNN algorithm correctly detects faces. Let's now extract this face from the image to perform further analysis on it.

1.4 Extract Face for Further Analysis

At this point, you know the coordinates of the faces from the detector. Extracting the faces is a fairly easy task using list indices. However, the VGGFace2 algorithm that we use needs the faces to be resized to 224 x 224 pixels. We'll use the PIL library to resize the images.

The function extract_face_from_image() extracts all faces from an image:

from numpy import asarray from PIL import Image def extract_face_from_image(image_path, required_size=(224, 224)): # load image and detect faces image = plt.imread(image_path) detector = MTCNN() faces = detector.detect_faces(image) face_images = [] for face in faces: # extract the bounding box from the requested face x1, y1, width, height = face['box'] x2, y2 = x1 + width, y1 + height # extract the face face_boundary = image[y1:y2, x1:x2] # resize pixels to the model size face_image = Image.fromarray(face_boundary) face_image = face_image.resize(required_size) face_array = asarray(face_image) face_images.append(face_array) return face_images extracted_face = extract_face_from_image('iacocca_1.jpg') # Display the first face from the extracted faces plt.imshow(extracted_face[0]) plt.show()

Here is how the extracted face looks from the first image.

Extracted and resized face from first imageExtracted and resized face from first image

The post Face Detection and Recognition with Keras appeared first on SitePoint.

React Native End-to-end Testing and Automation with Detox

Nov 6, 2019

Description:

Introducing Detox, a React Native End-to-end Testing and Automation Framework

Detox is an end-to-end testing and automation framework that runs on a device or a simulator, just like an actual end user.

Software development demands fast responses to user and/or market needs. This fast development cycle can result (sooner or later) in parts of a project being broken, especially when the project grows so large. Developers get overwhelmed with all the technical complexities of the project, and even the business people start to find it hard to keep track of all scenarios the product caters for.

In this scenario, there’s a need for software to keep on top of the project and allow us to deploy with confidence. But why end-to-end testing? Aren’t unit testing and integration testing enough? And why bother with the complexity that comes with end-to-end testing?

First of all, the complexity issue has been tackled by most of the end-to-end frameworks, to the extent that some tools (whether free, paid or limited) allow us to record the test as a user, then replay it and generate the necessary code. Of course, that doesn’t cover the full range of scenarios that you’d be able to address programmatically, but it’s still a very handy feature.

Want to learn React Native from the ground up? This article is an extract from our Premium library. Get an entire collection of React Native books covering fundamentals, projects, tips and tools & more with SitePoint Premium. Join now for just $9/month.

End-to-end Integration and Unit Testing

End-to-end testing versus integration testing versus unit testing: I always find the word “versus” drives people to take camps — as if it’s a war between good and evil. That drives us to take camps instead of learning from each other and understanding the why instead of the how. The examples are countless: Angular versus React, React versus Angular versus Vue, and even more, React versus Angular versus Vue versus Svelte. Each camp trash talks the other.

jQuery made me a better developer by taking advantage of the facade pattern $('') to tame the wild DOM beast and keep my mind on the task at hand. Angular made me a better developer by taking advantage of componentizing the reusable parts into directives that can be composed (v1). React made me a better developer by taking advantage of functional programming, immutability, identity reference comparison, and the level of composability that I don’t find in other frameworks. Vue made me a better developer by taking advantage of reactive programming and the push model. I could go on and on, but I’m just trying to demonstrate the point that we need to concentrate more on the why: why this tool was created in the first place, what problems it solves, and whether there are other ways of solving the same problems.

As You Go Up, You Gain More Confidence

end-to-end testing graph that demonstrates the benefit of end-to-end testing and the confidence it brings

As you go more on the spectrum of simulating the user journey, you have to do more work to simulate the user interaction with the product. But on the other hand, you get the most confidence because you’re testing the real product that the user interacts with. So, you catch all the issues—whether it’s a styling issue that could cause a whole section or a whole interaction process to be invisible or non interactive, a content issue, a UI issue, an API issue, a server issue, or a database issue. You get all of this covered, which gives you the most confidence.

Why Detox?

We discussed the benefit of end-to-end testing to begin with and its value in providing the most confidence when deploying new features or fixing issues. But why Detox in particular? At the time of writing, it’s the most popular library for end-to-end testing in React Native and the one that has the most active community. On top of that, it’s the one React Native recommends in its documentation.

The Detox testing philosophy is “gray-box testing”. Gray-box testing is testing where the framework knows about the internals of the product it’s testing.In other words, it knows it’s in React Native and knows how to start up the application as a child of the Detox process and how to reload it if needed after each test. So each test result is independent of the others.

Prerequisites macOS High Sierra 10.13 or above Xcode 10.1 or above

Homebrew:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Node 8.3.0 or above:

brew update && brew install node

Apple Simulator Utilities: brew tap wix/brew and brew install applesimutils

Detox CLI 10.0.7 or above:

npm install -g detox-cli See the Result in Action

First, let’s clone a very interesting open-source React Native project for the sake of learning, then add Detox to it:

git clone https://github.com/ahmedam55/movie-swiper-detox-testing.git cd movie-swiper-detox-testing npm install react-native run-ios

Create an account on The Movie DB website to be able to test all the application scenarios. Then add your username and password in .env file with usernamePlaceholder and passwordPlaceholder respectively:

isTesting=true username=usernamePlaceholder password=passwordPlaceholder

After that, you can now run the tests:

detox test

Note that I had to fork this repo from the original one as there were a lot of breaking changes between detox-cli, detox, and the project libraries. Use the following steps as a basis for what to do:

Migrate it completely to latest React Native project. Update all the libraries to fix issues faced by Detox when testing. Toggle animations and infinite timers if the environment is testing. Add the test suite package. Setup for New Projects Add Detox to Our Dependencies

Go to your project’s root directory and add Detox:

npm install detox --save-dev Configure Detox

Open the package.json file and add the following right after the project name config. Be sure to replace movieSwiper in the iOS config with the name of your app. Here we’re telling Detox where to find the binary app and the command to build it. (This is optional. We can always execute react-native run-ios instead.) Also choose which type of simulator: ios.simulator, ios.none, android.emulator, or android.attached. And choose which device to test on:

{ "name": "movie-swiper-detox-testing", // add these: "detox": { "configurations": { "ios.sim.debug": { "binaryPath": "ios/build/movieSwiper/Build/Products/Debug-iphonesimulator/movieSwiper.app", "build": "xcodebuild -project ios/movieSwiper.xcodeproj -scheme movieSwiper -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build", "type": "ios.simulator", "name": "iPhone 7 Plus" } } } }

Here’s a breakdown of what the config above does:

Execute react-native run-ios to create the binary app. Search for the binary app at the root of the project: find . -name "*.app". Put the result in the build directory.

Before firing up the test suite, make sure the device name you specified is available (for example, iPhone 7). You can do that from the terminal by executing the following:

xcrun simctl list

Here’s what it looks like:

device-list

Now that weve added Detox to our project and told it which simulator to start the application with, we need a test runner to manage the assertions and the reporting—whether it’s on the terminal or otherwise.

Detox supports both Jest and Mocha. We’ll go with Jest, as it has bigger community and bigger feature set. In addition to that, it supports parallel test execution, which could be handy to speed up the end-to-end tests as they grow in number.

Adding Jest to Dev Dependencies

Execute the following to install Jest:

npm install jest jest-cli --save-dev

The post React Native End-to-end Testing and Automation with Detox appeared first on SitePoint.

How to Build Your First Amazon Alexa Skill

Nov 5, 2019

Description:

How to Build Your First Amazon Alexa Skill

Out of the box, Alexa supports a number of built-in skills, such as adding items to your shopping list or requesting a song. However, developers can build new custom skills by using the Alexa Skill Kit (ASK).

The ASK, a collection of APIs and tools, handles the hard work related to voice interfaces, including speech recognition, text-to-speech encoding, and natural language processing. ASK helps developers build skills quickly and easily.

In short, the sole reason that Alexa can understand a user’s voice commands is that it has skills defined. Every Alexa skill is a piece of software designed to understand voice commands. Also, each Alexa skill has its own logic defined that creates an appropriate response for the voice command. To give you an idea of some existing Alexa skills, they include:

ordering pizza at Domino's Pizza calling for an Uber telling you your horoscope

So as said, we can develop our own custom skills fitted to our need with the Alexa Skill Kit, a collection of APIs and tools designed for this purpose. The ASK includes tools like speech recognition, text-to-speech encoding, and natural language processing. The kit should get any developer started quickly with developing their own custom skill.

In this article, you’ll learn how to create a basic "get a fact" Alexa skill. In short, we can ask Alexa to present us with a random cat fact. The complete code for completing our task can be found on GitHub. Before we get started, let's make sure we understand the Alexa skill terminology.

Mastering Alexa Skill Terminology

First, let's learn how a user can interact with a custom skill. This will be important for understanding the different concepts related to skills.

In order to activate a particular skill, the user has to call Alexa and ask to open a skill. For example: "Alexa, open cat fact". By doing this, we're calling the invocation name of the skill. Basically, the invocation name can be seem as the name of the application.

Now that we've started the right skill, we have access to the voice intents/commands the skill understands. As we want to keep things simple, we define a "Get Cat Fact" intent. However, we need to provide sample sentences to trigger the intent. An intent can be triggered by many example sentences, also called utterances. For example, a user might say "Give a fact". Therefore, we define the following example sentences:

"Tell a fact" "Give a cat fact" "Give a fact"

It's even possible to combine the invocation name with an intent like this: "Alexa, ask Cat Fact to give a fact".

Now that we know the difference between an invocation name and intent, let's move on to creating your first Alexa skill.

Creating an Amazon Developer Account

To get started, we need an Amazon Developer Account. If you have one, you can skip this section.

Signing up for an Amazon Developer account is a three-step process. Amazon requires some personal information, accepting the terms of service, and providing a payment method. The advantage of signing up for an Amazon Developer account is that you get access to a plethora of other Amazon services. Once the signup has been successfully completed, you'll see the Amazon Developer dashboard.

Log yourself in to the dashboard and click on the Developer Console button in the top-right corner.

Open Developer Console

Next up, we want to open the Alexa Skills Kit.

Open Alexa Skills Kit

If you were unable to open the Alexa Skills Kit, use this link.

In the following section, we'll create our actual skill.

Creating Our First Custom Alexa Skill

Okay, we're set to create our first custom Alexa skill. Click the blue button Create Skill to open up the menu for creating a new skill.

Create Skill Button

Firstly, it will prompt us for the name of our skill. As you already know, we want random cat facts and therefore call the skill custom cat fact (we can't use cat fact as that's a built-in skill for Alexa devices). Next, it prompts us to pick a model for your skill. We can choose between some predefined models or go for a custom model that gives us full flexibility. As we don't want to be dealing with code we don't need, we go for the Custom option.

Note: If you choose a predefined skill, you get a list of interaction models and example sentences (utterances). However, even the custom skill is equipped with the most basic intents like Cancel, Help, NavigateHome, and Stop.

Pick Skill name

Next, we need to pick a way to host our skill. Again, we don't want to overcomplicate things and pick the Alexa-Hosted (Node.js) option. This means we don't have to run a back end ourselves that requires some effort to make it "Alexa compliant". It means you have to format the response according to the Amazon Alexa standards for a device to understand this. The Alexa-hosted option will:

host skills in your account up to the AWS Free Tier limits and get you started with a Node.js template. You will gain access to an AWS Lambda endpoint, 5 GB of media storage with 15 GB of monthly data transfer, and a table for session persistence.

Pick host method

Okay, now that all settings are in place, you can click the Create Skill button in the top-right corner of the screen. This button will generate the actual skill in our Amazon Developer account.

Modifying Your First Alexa Skill

Now if you navigate to the Alexa Developer Console, you'll find your skill listed there. Click the edit button to start modifying the skill.

Modify Alexa Skill

Next, Amazon will display the build tab for the Cat Fact skill. On the left-hand side, you'll find a list of intents that are defined for the skill. As said before, by default the Alexa Skills Kit generates a Cancel, Stop, Help, and NavigateHome intent. The first three are helpful for a user that wants to quit the skill or doesn't know how to use it. The last one, NavigateHome, is only used for complex skills that involve multiple steps.

Interaction model

Step 1: Verify Invocation Name

First of all, let's verify if the invocation name for the skill is correct. The name should say "custom cat fact".

In case you change the name, make sure to hit the Save Model button on top of the page.

Invocation name

The post How to Build Your First Amazon Alexa Skill appeared first on SitePoint.

How to Build a Web App with GraphQL and React

Nov 1, 2019

Description:

In this tutorial, we'll learn to build a web application with React and GraphQL. We'll consume an API available from graphql-pokemon and serve it from this link, which allows you to get information about Pokémon.

GraphQL is a query language for APIs and a runtime for fulfilling those queries created by Facebook. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

In this tutorial, we'll only learn the front end of a GraphQL application that makes use of Apollo for fetching data from a ready GraphQL API hosted on the web.

Let's get started with the prerequisites!

Prerequisites

There are a few prerequisites for this tutorial:

recent versions of Node.js and npm installed on your system knowledge of JavaScript/ES6 familiarity with React

If you don't have Node and npm installed on your development machine, you can simply download the binaries for your system from the official website. You can also use NVM, a POSIX-compliant bash script to manage multiple active Node.js versions.

Installing create-react-app

Let's install the create-react-app tool that allows you to quickly initialize and work with React projects.

Open a new terminal and run the following command:

npm install -g create-react-app

Note: You may need to use sudo before your command in Linux and macOS or use a command prompt with administrator rights if you get EACCESS errors when installing the package globally on your machine. You can also simply fix your npm permissions.

At the time of writing, this installs create-react-app v3.1.1.

Creating a React Project

Now we're ready to create our React project.

Go back to your terminal and run the following command:

create-react-app react-pokemon

Next, navigate into your project's folder and start the local development server:

cd react-pokemon npm start

Go to http://localhost:3000 in your web browser to see your app up and running.

This is a screenshot of the app at this point:

The current state of our app

Installing Apollo Client

Apollo Client is a complete data management solution that's commonly used with React, but can be used with any other library or framework.

Apollo provides intelligent caching that enables it to be a single source of truth for the local and remote data in your application.

You'll need to install the following packages in your React project to work with Apollo:

graphql: the JavaScript reference implementation for GraphQL apollo-client: a fully-featured caching GraphQL client with integrations for React, Angular, and more apollo-cache-inmemory: the recommended cache implementation for Apollo Client 2.0 apollo-link-http: the most common Apollo Link, a system of modular components for GraphQL networking react-apollo: this package allows you to fetch data from your GraphQL server and use it in building complex and reactive UIs using the React framework graphql-tag: this package provides helpful utilities for parsing GraphQL queries such as gql tag.

Open a new terminal and navigate to your project's folder, then run the following commands:

npm install graphql --save npm install apollo-client --save npm install apollo-cache-inmemory --save npm install apollo-link-http --save npm install react-apollo --save npm install graphql-tag --save

Now that we've installed the necessary packages, we need to create an instance of ApolloClient.

Open the src/index.js file and add the following code:

import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { HttpLink } from 'apollo-link-http'; const cache = new InMemoryCache(); const link = new HttpLink({ uri: 'https://graphql-pokemon.now.sh/' }) const client = new ApolloClient({ cache, link })

We first create an instance of InMemoryCache, then an instance of HttpLink and we pass in our GraphQL API URI. Next, we create an instance of ApolloClient and we provide the cache and link instances.

Connect the Apollo Client to React Components

After creating the instance of ApolloClient, we need to connect it to our React component(s).

We'll use the new Apollo hooks, which allows us to easily bind GraphQL operations to our UI.

We can connect Apollo Client to our React app by simply wrapping the root App component with the ApolloProvider component — which is exported from the @apollo/react-hooks package — and passing the client instance via the client prop.

The ApolloProvider component is similar to React's Context provider. It wraps your React app and places the client in the context, which enables you to access it from anywhere in your app.

Now let's import the ApolloProvider component in our src/index.js file and wrap the App component as follows:

The post How to Build a Web App with GraphQL and React appeared first on SitePoint.

How to Build Your First Discord Bot with Node.js

Oct 30, 2019

Description:

Nowadays, bots are being used for automating various tasks. Since the release of Amazon's Alexa devices, the hype surrounding automation bots has only started to grow. Besides Alexa, other communication tools like Discord and Telegram offer APIs to develop custom bots.

This article will solely focus on creating your first bot with the exposed Discord API. Maybe the most well-known Discord bot is the Music Bot. The music bot lets you type a song name and the bot will attach a new user to your channel who plays the requested song. It’s a commonly used bot among younger people on gaming or streaming servers.

Let’s get started with creating a custom Discord bot.

Prerequisites Node.js v10 or higher installed (basic knowledge) a Discord account and Discord client basic knowledge of using a terminal Step 1: Setup Test Server

First of all, we need a test server on which we can later test our Discord bot. We can create a new server by clicking the plus icon in the left bottom corner.

click create server

A pop-up will be displayed that asks you if you want to join a server or create a new one. Of course, we want to create a new server.

select create server

Next, we need to input the name for our server. To keep things simple, I've named the server discord_playground. If you want, you can change the server location depending on where you're located to get a better ping.

server name

If everything went well, you should see your newly created server.

new server

Step 2: Generating Auth Token

When we want to control our bot via code, we need to register the bot first under our Discord account.

To register the bot, go to the Discord Developers Portal and log in with your account.

After logging in, you should be able to see the dashboard. Let's create a new application by clicking the New Application button.

developer dashboard

Next, you'll see a pop-up that asks you to input a name for your application. Let's call our bot my-greeter-bot. By clicking the Create button, Discord will create an API application.

create application

When the application has been created, you'll see the overview of the newly created my-greeter-bot application. You'll see information like a client ID and client secret. This secret will be used later as the authorization token.

overview greeter bot

Now, click on the Bot menu option in the Settings menu. Discord will build our my-greeter-bot application and add a bot user to it.

add bot

When the bot has been built, you get an overview of your custom bot. Take a look at the Token section. Copy this authorization token and write it down somewhere, as we'll need it later to connect to our bot user.

bot tab overview

The post How to Build Your First Discord Bot with Node.js appeared first on SitePoint.

What Is Functional Programming?

Oct 29, 2019

Description:

As a programmer, you probably want to write elegant, maintainable, scalable, predictable code. The principles of functional programming, or FP, can significantly aid in these goals.

Functional programming is a paradigm, or style, that values immutability, first-class functions, referential transparency, and pure functions. If none of those words makes sense to you, don't worry! We're going to break down all this terminology in this article.

Functional programming evolved from lambda calculus, a mathematical system built around function abstraction and generalization. As a result, a lot of functional programming languages look very mathematical. Good news, though: you don't need to use a functional programming language to bring functional programming principles to your code. In this post, we'll use JavaScript, which has a lot of features that make it amenable to functional programming while not being tied to that paradigm.

The Core Principles of Functional Programming

Now that we've discussed what functional programming is, let's talk about the core principles behind FP.

The post What Is Functional Programming? appeared first on SitePoint.

6 Tools for Debugging React Native

Oct 28, 2019

Description:

Debugging is an essential part of software development. It’s through debugging that we know what’s wrong and what’s right, what works and what doesn’t. Debugging provides the opportunity to assess our code and fix problems before they’re pushed to production.

debugging featured image

In the React Native world, debugging may be done in different ways and with different tools, since React Native is composed of different environments (iOS and Android), which means there’s an assortment of problems and a variety of tools needed for debugging.

Thanks to the large number of contributors to the React Native ecosystem, many debugging tools are available. In this brief guide, we’ll explore the most commonly used of them, starting with the Developer Menu.

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. — Brian W. Kernighan

The Developer Menu

the developer menu

The in-app developer menu is your first gate for debugging React Native, it has many options which we can use to do different things. Let’s break down each option.

Reload: reloads the app Debug JS Remotely: opens a channel to a JavaScript debugger Enable Live Reload: makes the app reload automatically on clicking Save Enable Hot Reloading: watches for changes accrued in a changed file Toggle Inspector: toggles an inspector interface, which allows us to inspect any UI element on the screen and its properties, and presents and interface that has other tabs like networking, which shows us the HTTP calls, and a tab for performance.

The post 6 Tools for Debugging React Native appeared first on SitePoint.

Why Your Agency Should Offer Managed Cloud Hosting to Clients

Oct 28, 2019

Description:

This article was created in partnership with Cloudways. Thank you for supporting the partners who make SitePoint possible.

When it comes to end-to-end services, digital agencies offer an impressive range. From requirement analysis to post-deployment maintenance, these agencies do everything to make sure that their clients are able to fully leverage their projects for maximum business efficiency.

In this backdrop, many agencies (particularly those that deal with web-based projects) also offer hosting as part of their services to their customers. While small and up-and-coming digital agencies might not have hosting on their service brochure, mid-tier and top-shelf agencies see hosting as an integral service offering to their clients.

Setting up Hosting for Customers

For a web-based project, web hosting is an essential component that determines the success (and failure) of the project. Since the agency has developed the project, many clients trust the agency-managed hosting for their project.

High-performance applications (online stores and CRM in particular) demand a hosting solution that’s able to keep pace with the high request volume and a large number of concurrent connections. Clients with these projects can’t compromise on the post-deployment performance of the applications. As such, agencies prefer an in-house hosting setup that caters to the specific requirements of the projects.

Agencies Benefit From In-house Hosting

Before going into what benefits agencies get from an in-house hosting setup, it’s important to understand the major requirements of high-performance projects. Without going too much into the details, in-house hosting solutions are set up to make sure that custom-built projects continue to perform on the following parameters:

the number of visitors per hour/day/month the number of simultaneous visitors the maximum number of connections allowed the number of simultaneous requests/orders the size and complexity of the products catalog (number of products, product categories, attributes) the content requirements and traffic on content assets such as blogs the volume of search queries on the site the size and connections on the database

With in-house hosting solutions, agencies (and their clients) get a whole range of benefits such as those outlined below.

Custom Hardware and Software

Hardware requirements for custom, high-performance projects generally include three components: CPU, RAM and Disk Space. Since each project has custom requirements that are often not available in off-the-shelf hosting solutions available in the market, agencies opt for setting up in-house hardware platforms for their customers.

Custom hardware setups usually cost more than the conventional, commercially available hosting hardware architecture. The cost of setting up and maintaining the hosting architecture is usually the responsibility of the dev agency, which usually bills the client for these services.

Another related (and in my opinion, more important) requirement of these projects is a custom environment that comprises an OS layer and a facilitation layer made of servers and caches. A custom environment allows agencies to build their projects without worrying about conflicts with the OS and server software required to execute the codebase. Thanks to in-house hosting, digital agencies can completely customize the OS and server layer to the project specifications.

End-to-End Management of Project Hosting

Project requirements change and clients often revise their requirements and scope. These changes also impact the hosting requirements and specifications. Since the hosting process is being managed in-house, the agency can take proactive actions to improve hosting setup specifications and ensure continued performance for the application.

Passive Income Stream

In almost all cases, agency-managed hosting solutions are built and maintained on the client’s dollars. The agency proposes hosting setup specifications and sets it up once the client pays for it. Once the setup is active, the client pays for the maintenance and upkeep of the hosting solution. This is a passive income channel that is often an important supplement to agency revenues.

Challenges In-agency Managed Hosting

Despite the benefits, managing an in-house hosting setup can prove to be a drag on the agency operations. In particular, agency-managed hosting causes the following challenges for the business processes.

Hosting Architecture Requires Continuous Attention

Since this is an in-house managed hosting solution, it’s obvious that the agency is responsible for keeping both the hardware and software layers operational. While the hardware layer (the physical server machines and the networking equipment) have a lower ratio of failure, it’s important to note that the software components of the hosting solution require detailed attention and upkeep.

Both hardware and software vendors regularly release patches that fix bugs and enhance product functionality. In many cases, these patches are mission-critical and essential for the continued performance of the project’s hosting. In in-house managed hosting, this is the responsibility of a dedicated team that performs no other function.

The Constant Need for Security

Web servers are the prime target of cybercriminals because of the wealth of information and user data on them. The problem with server security is that it's a full-time function that requires specialists on the team. The same goes for clients’ applications (CMSs such as WordPress are especially vulnerable) that could potentially open up security loopholes in the server and application security. Not many agencies can afford a dedicated infosec expert on the payroll. Thus, there's always the danger that clients’ applications can get hacked because the agency-managed hosting is unable to maintain the required security standards.

Sysadmins Prove to be an Overhead

Sysadmins are among the highest-paid professions in the ICT industry, and rightly so! They manage entire data centers and handle all aspects of hosting servers from provisioning to maintenance. The problem with sysadmins is the high recruitment and operational costs of these professionals. Thus, hiring a sysadmin to manage in-house hosting is a serious decision that's out of the budget of many dev agencies.

Deviation from the Core Business

Digital agencies are in the business of building applications and custom projects that create value for their clients. An in-house hosting solution requires competence that lies outside the normal scope of the dev agencies. In addition, managing hosting solutions require expenses that eat away into profits without generating enough revenue to justify their inclusion in business offerings.

Shared Hosting is a False Start

The good news is that many agencies are aware of the issues with in-house, agency-managed hosting and have come to realize that this is not the ideal solution for managing clients’ hosting focused expectations.

However, since the clients’ requirements continue to grow and the need for hosting solutions for custom-developed apps is on the rise, a number of agencies have turned to shared hosting as an alternative to agency managed in-house hosting solutions.

When opting for shared hosting solutions, agencies try to reduce the cost of hosting solutions while providing a comparable hosting solution to the clients.

Before going into the description of why shared hosting solutions are in fact counterproductive for dev agencies, it's important to understand how shared hosting solutions work.

Shared Hosting in a Nutshell

As the name implies, shared hosting is a solution where several websites/applications are hosted on a single physical server. This means that the physical resources (CPU, RAM, Disk space and bandwidth (in some cases) get shared among the websites hosted on the server.

While this is not a bad solution per se, it's not the right ft for high-performance applications. These applications have a minimum server resource requirements that often exceed the allocated “quota” allocated by the shared hosting server.

Many digital agencies try to integrate shared hosting solutions in their customer-focused services by eliminating sysadmins from the equation and asking the developers to manage the hosting servers for the clients.

The post Why Your Agency Should Offer Managed Cloud Hosting to Clients appeared first on SitePoint.

How to Build a Tic Tac Toe Game with Svelte

Oct 24, 2019

Description:

How to Build a Tic Tac Toe Game with Svelte

Svelte is a next generation way of building user interfaces.

While frameworks like React, Vue and Angular do the bulk of their work in the browser, Svelte takes it to the next level. It does its work when you build the app and it compiles your Svelte app to efficient vanilla JavaScript. So you get the best of both worlds. You write your code in Svelte which makes it easy to read, re-use and all the other benefits you get when you use a framework, and it makes for a blazing-fast web app as it complies down to vanilla JavaScript so that you don’t have the overhead of the JavaScript framework you’re using.

Svelte allows you to write less code. It also doesn’t use the concept of the Virtual DOM popularized by React. It instead surgically updates the DOM when the state of the app changes so the app starts fast and stays fast.

Prerequisites

For this tutorial, you need a basic knowledge of HTML, CSS and JavaScript.

You must also have installed the latest version of Node.js.

We’ll also be using npx, which comes installed by default with Node.js.

Throughout this tutorial we’ll be using yarn. If you don’t have yarn already installed, install it from here.

To make sure we’re on the same page, these are the versions used in this tutorial:

Node 12.10.0 npx 6.11.3 yarn 1.17.3 Getting Started with Svelte

In this tutorial, we’ll be building a Tic Tac Toe game in Svelte. By the end, you’ll be able to get up and running quickly with Svelte and get started in building your own apps in Svelte.

To get started, we must scaffold our app using degit. degit is more or less the same as git clone, but much quicker. You can learn more about it here.

Go ahead and make a new project by typing the following in the terminal:

$ npx degit sveltejs/template tic-tac-toe-svelte

npx lets you use the degit command without installing it globally.

Before npx, we would have to do the two following steps to achieve the same result:

$ npm install --global degit $ degit sveltejs/template tic-tac-toe-svelte

Thanks to npx, we don’t bloat our global namespace, and we always use the latest version of degit.

degit clones the repo https://github.com/sveltejs/template into a tic-tac-toe-svelte folder.

Go ahead into the tic-tac-toe-svelte directory and install the dependencies by typing the following in the terminal:

$ cd tic-tac-toe-svelte $ yarn

Now run the application by typing the following in the terminal:

$ yarn dev

Now open up the browser and go to http://localhost:5000 and you should see the following:

Svelte - Hello World

If you go into the src/ folder, you’ll see two files, App.svelte and main.js. main.js is the entry point of a Svelte app.

Open up the main.js and you should see the following:

import App from './App.svelte'; const app = new App({ target: document.body, props: { name: 'world' } }); export default app;

The above file imports App.svelte and instantiates it using a target element. It puts the component on the DOM’s document.body. It also passes name props to the App component. This prop will be accessed in App.svelte.

Components in Svelte are written using .svelte files which contain HTML, CSS and JavaScript. This will look familiar if youse worked with Vue.

Now open up App.svelte and you should see the following:

<script> export let name; </script> <style> h1 { color: purple; } </style> <h1>Hello {name}!</h1>

Firstly, we have the script tag inside, in which we have a named export called name. This should be similar to the prop mentioned in main.js.

Then we have a style tag that lets us style all the elements in that particular file, which is scoped to that file only so there’s no issue of cascading.

Then, at the bottom, we have an h1 tag, inside which we have Hello {name}!. The name in curly brackets will be replaced by the actual value. This is called value interpolation. That’s why Hello world! is printed on the screen.

Basic Structure of a Svelte Component

All .svelte files will basically have the following structure:

<script> /* Javascript logic */ </script> <style> /* CSS styles */ </style> <!-- HTML markup -->

The HTML markup will have some additional Svelte-specific syntax, but the rest is just plain HTML, CSS and JavaScript.

Making Tic Tac Toe in Svelte

Let’s get started with building our Tic Tac Toe game.

Replace main.js with the following:

import App from './App.svelte' const app = new App({ target: document.body, }) export default app

We’ve basically removed the props property from App component instantiation.

Now replace App.svelte with the following:

<script> const title = "Tic Tac Toe"; </script> <svelte:head> <title>{title}</title> </svelte:head> <h1>{title}</h1>

Here, we initialize a constant variable title with a string Tic Tac Toe.

Then, in the markup below, we use a special Svelte syntax, svelte:head, to set the title property in the head tag.

This is basically similar to doing this:

<head> <title>Tic Tac Toe</title> </head>

But the advantage of using the svelte:head syntax is that the title can be changed at runtime.

We then use the same title property in our h1 tag. It should now look like this:

Svelte - Tic Tac Toe

Now create two other files in the src/ directory named Board.svelte and Square.svelte.

Open Square.svelte and paste in the following:

<script> export let value; </script> <style> .square { flex: 1 0 25%; width: 50px; height: 70px; background-color: whitesmoke; border: 2px solid black; margin: 5px; padding: 5px; font-size: 20px; text-align: center; } .square:hover { border: 2px solid red; } </style> <button class="square">{value}</button>

Basically, we’re creating a button and styling it.

Now open up Board.svelte and paste the following:

<script> import Square from "./Square.svelte"; let squares = [null, null, null, null, null, null, null, null, null]; </script> <style> .board { display: flex; flex-wrap: wrap; width: 300px; } </style> <div class="board"> {#each squares as square, i} <Square value={i} /> {/each} </div>

Here we’ve imported the Square component. We’ve also initialized the squares array, which will contain our X and 0’s data which is currently null.

The post How to Build a Tic Tac Toe Game with Svelte appeared first on SitePoint.

How to Install Docker on Windows 10 Home

Oct 22, 2019

Description:

How to Install Docker on Windows 10 Home

If you've ever tried to install Docker for Windows, you've probably came to realize that the installer won't run on Windows 10 Home. Only Windows Pro, Enterprise or Education support Docker. Upgrading your Windows license is pricey, and also pointless, since you can still run Linux Containers on Windows without relying on Hyper-V technology, a requirement for Docker for Windows.

If you plan on running Windows Containers, you'll need a specific version and build of Windows Server. Check out the Windows container version compatibility matrix for details.

99.999% of the time, you only need a Linux Container, since it supports software built using open-source and .NET technologies. In addition, Linux Containers can run on any distro and on popular CPU architectures, including x86_64, ARM and IBM.

In this tutorial, I'll show you how to quickly setup a Linux VM on Windows Home running Docker Engine with the help of Docker Machine. Here's a list of software you'll need to build and run Docker containers:

Docker Machine: a CLI tool for installing Docker Engine on virtual hosts Docker Engine: runs on top of the Linux Kernel; used for building and running containers Docker Client: a CLI tool for issuing commands to Docker Engine via REST API Docker Compose: a tool for defining and running multi-container applications

I'll show how to perform the installation in the following environments:

On Windows using Git Bash On Windows Subsystem for Linux 2 (running Ubuntu 18.04)

First, allow me to explain how the Docker installation will work on Windows.

How it Works

As you probably know, Docker requires a Linux kernel to run Linux Containers. For this to work on Windows, you'll need to set up a Linux virtual machine to run as guest in Windows 10 Home.

docker windows home

Setting up the Linux VM can be done manually. The easiest way is to use Docker Machine to do this work for you by running a single command. This Docker Linux VM can either run on your local system or on a remote server. Docker client will use SSH to communicate with Docker Engine. Whenever you create and run images, the actual process will happen within the VM, not on your host (Windows).

Let's dive into the next section to set up the environment needed to install Docker.

Initial Setup

You may or may not have the following applications installed on your system. I'll assume you don't. If you do, make sure to upgrade to the latest versions. I'm also assuming you're running the latest stable version of Windows. At the time of writing, I'm using Windows 10 Home version 1903. Let's start installing the following:

Install Git Bash for Windows. This will be our primary terminal for running Docker commands.

Install Chocolatey, a package manager for Windows. It will make the work of installing the rest of the programs easier.

Install VirtualBox and its extension. Alternatively, If you have finished installing Chocolatey, you can simply execute this command inside an elevated PowerShell terminal:

C:\ choco install virtualbox

If you'd like to try running Docker inside the WSL2 environment, you'll need to set up WSL2 first. You can follow this tutorial for step-by-step instructions.

Docker Engine Setup

Installing Docker Engine is quite simple. First we need to install Docker Machine.

Install Docker Machine by following instructions on this page. Alternatively, you can execute this command inside an elevated PowerShell terminal:

C:\ choco install docker-machine

Using Git Bash terminal, use Docker Machine to install Docker Engine. This will download a Linux image containing the Docker Engine and have it run as a VM using VirtualBox. Simply execute the following command:

$ docker-machine create --driver virtualbox default

Next, we need to configure which ports are exposed when running Docker containers. Doing this will allow us to access our applications via localhost<:port>. Feel free to add as many as you want. To do this, you'll need to launch Oracle VM VirtualBox from your start menu. Select default VM on the side menu. Next click on Settings > Network > Adapter 1 > Port Forwarding. You should find the ssh forwarding port already set up for you. You can add more like so:

docker vm ports

Next, we need to allow Docker to mount volumes located on your hard drive. By default, you can only mount from the C://Users/ directory. To add a different path, simply go to Oracle VM VirtualBox GUI. Select default VM and go to Settings > Shared Folders. Add a new one by clicking the plus symbol. Enter the fields like so. If there's an option called Permanent, enable it.

docker vm volumes

To get rid of the invalid settings error as seen in the above screenshot, simply increase Video Memory under the Display tab in the settings option. Video memory is not important in this case, as we'll run the VM in headless mode.

To start the Linux VM, simply execute this command in Git Bash. The Linux VM will launch. Give it some time for the boot process to complete. It shouldn't take more than a minute. You'll need to do this every time you boot your host OS:

$ docker-machine start vbox

Next, we need to set up our Docker environment variables. This is to allow the Docker client and Docker Compose to communicate with the Docker Engine running in the Linux VM, default. You can do this by executing the commands in Git Bash:

# Print out docker machine instance settings $ docker-machine env default # Set environment variables using Linux 'export' command $ eval $(docker-machine env default --shell linux)

You'll need to set the environment variables every time you start a new Git Bash terminal. If you'd like to avoid this, you can copy eval output and save it in your .bashrc file. It should look something like this:

export DOCKER_TLS_VERIFY="1" export DOCKER_HOST="tcp://192.168.99.101:2376" export DOCKER_CERT_PATH="C:\Users\Michael Wanyoike\.docker\machine\machines\default" export DOCKER_MACHINE_NAME="default" export COMPOSE_CONVERT_WINDOWS_PATHS="true"

IMPORTANT: for the DOCKER_CERT_PATH, you'll need to change the Linux file path to a Windows path format. Also take note that there's a chance the IP address assigned might be different from the one you saved every time you start the default VM.

In the next section, we'll install Docker Client and Docker Compose.

The post How to Install Docker on Windows 10 Home appeared first on SitePoint.

6 Top VPNs for Web Developers to Choose

Oct 21, 2019

Description:

This article was created by VPN Review. Thank you for supporting the partners who make SitePoint possible.

Do you need a VPN? You're probably familiar with them, but they work like this: you connect to a server, all your internet queries pass through it as an intermediary, and they are passed on from this server to the external net. You can use a VPN to, for example, bypass geographic content restrictions by connecting to a server in the appropriate country.

For web developers, these features are essentially useful. First, when it's necessary to connect to sensitive development servers from outside networks, a VPN can make it safer by encrypting the traffic passing through your local network. This reduces the danger that the information you send to those servers will be accessed by hackers. And while testing geolocation features, a VPN allows you to connect as a user from the appropriate destination.

The downside is that the VPN needs to have access to your packets in order to relay them. You need to choose VPNs carefully, and it's especially worth being careful with new services, and even free ones. Note that it's important to use your company's VPN for development, or a service that has been approved for usage by your team.

To choose a service one should carefully read all the VPN Reviews on the web, search for the experts' opinions, and consider the product's reputation.

Let's analyze the most widespread VPN services:

The post 6 Top VPNs for Web Developers to Choose appeared first on SitePoint.

A Beginner’s Guide to Keras: Digit Recognition in 30 Minutes

Oct 18, 2019

Description:

A Beginner's Guide to Keras

Over the last decade, the use of artificial neural networks (ANNs) has increased considerably. People have used ANNs in medical diagnoses, to predict Bitcoin prices, and to create fake Obama videos! With all the buzz about deep learning and artificial neural networks, haven't you always wanted to create one for yourself? In this tutorial, we'll create a model to recognize handwritten digits.

We use the keras library for training the model in this tutorial. Keras is a high-level library in Python that is a wrapper over TensorFlow, CNTK and Theano. By default, Keras uses a TensorFlow backend by default, and we'll use the same to train our model.

Artificial Neural Networks Artificial neural networkImage source

An artificial neural network is a mathematical model that converts a set of inputs to a set of outputs through a number of hidden layers. An ANN works with hidden layers, each of which is a transient form associated with a probability. In a typical neural network, each node of a layer takes all nodes of the previous layer as input. A model may have one or more hidden layers.

ANNs receive an input layer to transform it through hidden layers. An ANN is initialized by assigning random weights and biases to each node of the hidden layers. As the training data is fed into the model, it modifies these weights and biases using the errors generated at each step. Hence, our model "learns" the pattern when going through the training data.

Convoluted Neural Networks

In this tutorial, we're going to identify digits — which is a simple version of image classification. An image is essentially a collection of dots or pixels. A pixel can be identified through its component colors (RGB). Therefore, the input data of an image is essentially a 2D array of pixels, each representing a color.

If we were to train a regular neural network based on image data, we'd have to provide a long list of inputs, each of which would be connected to the next hidden layer. This makes the process difficult to scale up.

Convolutional Neural Network ArchitectureConvolutional Neural Network Architecture

In a convoluted neural network (CNN), the layers are arranged in a 3D array (X-axis coordinate, Y-axis coordinate and color). Consequently, a node of the hidden layer would only be connected to a small region in the vicinity of the corresponding input layer, making the process far more efficient than a traditional neural network. CNNs, therefore, are popular when it comes to working with images and videos.

Convolutional Neural Network LayersConvolutional Neural Network Layers

The various types of layers in a CNN are as follows:

convolutional layers: these run input through certain filters, which identify features in the image pooling layers: these combine convolutional features, helping in feature reduction flatten layers: these convert an N-dimentional layer to a 1D layer classification layer: the final layer, which tells us the final result.

Let's now explore the data.

Explore MNIST Dataset

As you may have realized by now, we need labelled data to train any model. In this tutorial, we'll use the MNIST dataset of handwritten digits. This dataset is a part of the Keras package. It contains a training set of 60000 examples, and a test set of 10000 examples. We'll train the data on the training set and validate the results based on the test data. Further, we'll create an image of our own to test whether the model can correctly predict it.

First, let's import the MNIST dataset from Keras. The .load_data() method returns both the training and testing datasets:

from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data()

Let's try to visualize the digits in the dataset. If you're using Jupyter notebooks, use the following magic function to show inline Matplotlib plots:

%matplotlib inline

Next, import the pyplot module from matplotlib and use the .imshow() method to display the image:

import matplotlib.pyplot as plt image_index = 35 print(y_train[image_index]) plt.imshow(x_train[image_index], cmap='Greys') plt.show()

The label of the image is printed and then the image is displayed.

label printed and image displayed

Let's verify the sizes of the training and testing datasets:

print(x_train.shape) print(x_test.shape)

Notice that each image has the dimensions 28 x 28:

(60000, 28, 28) (10000, 28, 28)

Next, we may also wish to explore the dependent variable, stored in y_train. Let's print all labels until the digit that we visualized above:

print(y_train[:image_index + 1]) [5 0 4 1 9 2 1 3 1 4 3 5 3 6 1 7 2 8 6 9 4 0 9 1 1 2 4 3 2 7 3 8 6 9 0 5] Cleaning Data

Now that we've seen the structure of the data, let's work on it further before creating the model.

To work with the Keras API, we need to reshape each image to the format of (M x N x 1). We'll use the .reshape() method to perform this action. Finally, normalize the image data by dividing each pixel value by 255 (since RGB value can range from 0 to 255):

# save input image dimensions img_rows, img_cols = 28, 28 x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) x_train /= 255 x_test /= 255

Next, we need to convert the dependent variable in the form of integers to a binary class matrix. This can be achieved by the to_categorical() function:

from keras.utils import to_categorical num_classes = 10 y_train = to_categorical(y_train, num_classes) y_test = to_categorical(y_test, num_classes)

We're now ready to create the model and train it!

The post A Beginner’s Guide to Keras: Digit Recognition in 30 Minutes appeared first on SitePoint.

8 Ways to Style React Components Compared

Oct 17, 2019

Description:

8 Ways to Style React Components Compared

I've been working with a couple of developers in my office on React JS projects, who have varied levels of React JS experience. We've been solving some crazy problems like handling the weird way Redux does state initialization and making an axios request payload work with PHP and understanding what goes on in the background. This article arose out of a question about how to style React components.

The Various Styling Approaches

There are various ways to style React Components. Choosing the right method for styling components isn't a perfect absolute. It's a specific decision that should serve your particular use case, personal preferences and above all, architectural goals of the way you work. For example, I make use of notifications in React JS using Noty, and the styling should be able to handle plugins too.

Some of my goals in answering the question included covering these:

Global namespacing Dependencies Reusability Scalability Dead-code Elimination

There seems to be about eight different ways of styling React JS components used widely in the industry for production level work:

Inline CSS Normal CSS CSS in JS Styled Components CSS Modules Sass & SCSS Less Stylable

For each method, I'll look at the need for dependencies, the difficulty level, and whether or not the approach is really a good one or not.

Inline CSS Dependencies: None Difficulty: Easy Approach: Worst

I don't think anyone needs an introduction to inline CSS. This is the CSS styling sent to the element directly using the HTML or JSX. You can include a JavaScript object for CSS in React components. There are a few restrictions like replacing every - with camelCase text. You can style them in two ways using JavaScript objects as shown in the example.

Example import React from "react"; const spanStyles = { color: "#fff", borderColor: "#00f" }; const Button = props => ( <button style={{ color: "#fff", borderColor: "#00f" }}> <span style={spanStyles}>Button Name</span> </button> ); Regular CSS Dependencies: None Difficulty: Easy Approach: Okay

Regular CSS is a common approach, arguably one step better than inline CSS. The styles can be imported to any number of pages and elements unlike inline CSS, which is applied directly to the particular element. Normal CSS has several advantages, such as decreasing the file size with a clean code structure.

You can maintain any number of style sheets, and it can be easier to change or customize styles when needed. But regular CSS might be a major problem if you're working on a bigger project with lots of people involved, especially without an agreed pattern to do styling in CSS.

Example a:link { color: gray; } a:visited { color: green; } a:hover { color: rebeccapurple; } a:active { color: teal; } More Information

You can read more about regular CSS usage of the W3C's Learning CSS page. There are many playgrounds like JS Bin - Collaborative JavaScript Debugging, JSFiddle, CodePen: Build, Test, and Discover Front-end Code, Repl.it - The world's leading online coding platform, etc. where you can try them out live and get the results in real time.

CSS in JS Dependencies: jss, jss-preset-default, jss-cli Difficulty: Easy Approach: Decent

CSS in JS is an authoring tool for CSS which allows you to use JavaScript to describe styles in a declarative, conflict-free and reusable way. It can compile in the browser, on the server side or at build time in Node. It uses JavaScript as a language to describe styles in a declarative and maintainable way. It's a high performance JS-to-CSS compiler which works at runtime and server-side. When thinking in components, you no longer have to maintain a bunch of style sheets. CSS-in-JS abstracts the CSS model to the component level, rather than the document level (modularity).

Example import React from "react"; import injectSheet from "react-jss"; // Create your Styles. Remember, since React-JSS uses the default preset, // most plugins are available without further configuration needed. const styles = { myButton: { color: "green", margin: { // jss-expand gives more readable syntax top: 5, // jss-default-unit makes this 5px right: 0, bottom: 0, left: "1rem" }, "& span": { // jss-nested applies this to a child span fontWeight: "bold" // jss-camel-case turns this into 'font-weight' } }, myLabel: { fontStyle: "italic" } }; const Button = ({ classes, children }) => ( <button className={classes.myButton}> <span className={classes.myLabel}>{children}</span> </button> ); // Finally, inject the stylesheet into the component. const StyledButton = injectSheet(styles)(Button); More Information

You can learn more about this approach in the JSS official documentation. There's also a way to try it out using their REPL (Read-eval-print Loop).

Styled Components Dependencies: styled-components Difficulty: Medium Approach: Decent

Styled-components is an example of the above-mentioned CSS in JS. It basically gives us CSS with other properties you wish we had in CSS like nesting. It also allows us to style the CSS under the variable created in JavaScript. You could normally create a React component along with the styles attached to it without having to create a separate file for CSS. Styled-components allows us to create custom reusable components which can be less of a hassle to maintain. Props can be used in styling the components in the same way it is passed in the React components. Props are used instead of classes in CSS and set the properties dynamically.

Example import React from "react"; import styled, { css } from "styled-components"; const Button = styled.button` cursor: pointer; background: transparent; font-size: 16px; border-radius: 3px; color: palevioletred; margin: 0 1em; padding: 0.25em 1em; transition: 0.5s all ease-out; ${props => props.primary && css` background-color: white; color: green; border-color: green; `}; `; export default Button; More Information

Styled-components has a detailed documentation and the site also provides a live editor where you can try out the code. Get more information on styled components at styled-components: Basics.

CSS Modules Dependencies: css-loader Difficulty: Tough (Uses Loader Configuration) Approach: Better

If you've ever felt like the CSS global scope problem takes up most of your time when you have to find what a particular style does, or if you've had to write a CSS file without organizing it properly to make the code work first, or if getting rid of the files gives you a slight nudge in your heart wondering if you might break the whole code, I feel you. CSS Modules make sure that all of the styles for a component are at one single place and apply to that particular component. This certainly solves the global scope problem of CSS. The composition feature acts as a weapon to represent shared styles between the states. It's similar to the mixin in Sass, making it possible to combine multiple groups of styles.

Example import React from "react"; import style from "./panel.css"; const Panel = () => ( <div className={style.panelDefault}> <div className={style.panelBody}>A Basic Panel</div> </div> ); export default Panel; .panelDefault { border-color: #ddd; } .panelBody { padding: 15px; } Sass & SCSS Dependencies: node-sass Difficulty: Easy Approach: Best

Sass claims that it's the most mature, stable, and powerful professional grade CSS extension language in the world. It's a CSS preprocessor, which adds special features such as variables, nested rules and mixins (sometimes referred to as “syntactic sugar”) into regular CSS. The aim is to make the coding process simpler and more efficient. Just like other programming languages, Sass allows the use of variables, nesting, partials, imports and functions, which add super powers to regular CSS.

Example $font-stack: 'Open Sans', sans-serif; $primary-color: #333; body { font: 100% $font-stack; color: $primary-color; } More Information

Learn more about using and installing Sass with a variety of programming languages from their official documentation at Sass: Syntactically Awesome Style Sheets. If you want to try something out, there’s a service called SassMeister - The Sass Playground! where you can play around with different features of Sass and SCSS.

The post 8 Ways to Style React Components Compared appeared first on SitePoint.

Improving the Customer Journey with Flatfile’s Data Importer

Oct 17, 2019

Description:

This article was created in partnership with Flatfile.io. Thank you for supporting the partners who make SitePoint possible.

Close your eyes and imagine what it is like to import data into your application. Now open them.

Does it look something like this?

When creating a new or improving an existing product, building useful features is, of course, priority number one. What many forget, though, is that in innovation is wasted when the product experience is not intuitive. When crafting the customer journey, a product manager must pay particular attention to the customer's first steps.

In many products, the data importing process is one of those early steps. Unfortunately, it is often a major pain point for the customer. This isn't all the PM's fault; we've come to expect data import to be a lousy software experience. So we keep sending customers to complex templates, long support articles, and cryptic error screens, often within the first few minutes of their journey.

Not anymore, though. Flatfile offers a simple solution: an intuitive, plug-and-play data importer.

What Is Flatfile?

Flatfile offers software companies an alternative to building their own data importers.

For users, that means no more jumping through hoops to upload their data. Now, they can use Flatfile's platform instead for a seamless, smooth, and supportive data importing experience. Flatfile is designed to support users of any technical skill level: firefighters, real estate agents, and data analysts all leverage the Flatfile Importer.

For PMs, that means no more worrying about handling the UX and engineering complexities of data import. Instead of planning a whole sprint - if not several - on building a custom solution, PMs can hand their engineering team Flatfile's documentation and get an elegant, crafted experience in a day. Put simply, Flatlife takes the pain out of building and maintaining a data importer, and lets product teams focus on innovative, differentiating features.

How Does Flatfile Work?

Flatlife lets users upload their spreadsheets with just a few clicks. They can also manually enter their data.

Once the data has been uploaded, Flatfile asks the user a few simple questions about how their spreadsheet matches to your product, ensuring that the data is aligned with the correct field (e.g. first name, last name, email address, etc.).

The final step is data repair, where the user can review and update their import to correct any data errors. These errors appear based on validations you can pre-define, ensuring the tidiness of data before it ever hits your product database.

Once these steps are complete, the user is back in your application, and you have a clean, structured set of JSON data that's easy to pull into any database.

Meghann, Product Lead at Digsy.ai says: "When we were looking for solutions, we knew we could either build it ourselves or try to find something. Our product lead at the time heard of Flatfile. He presented it to the team, and ultimately we decided to implement Flatfile. We didn't see anything else on the market."

Why Should You Choose Flatfile?

When a user is importing data to your product, they want to use it and they want to see its value. Don't let them get hung up on spreadsheet templates and intimidating documentation. Flatfile takes most organizations less than a week to implement, and it gives users a simple, smooth, and delightful data import experience. Get started with a 30 day free trial and see how Flatfile.io can improve your customer journey.

Visit Flatfile.io.

The post Improving the Customer Journey with Flatfile’s Data Importer appeared first on SitePoint.

Build a JavaScript Command Line Interface (CLI) with Node.js

Oct 16, 2019

Description:

Build a Node CLI

As great as Node.js is for “traditional” web applications, its potential uses are far broader. Microservices, REST APIs, tooling, working with the Internet of Things and even desktop applications: it’s got your back.

Another area where Node.js is really useful is for building command-line applications — and that’s what we’re going to be doing in this article. We’re going to start by looking at a number of third-party packages designed to help work with the command line, then build a real-world example from scratch.

What we’re going to build is a tool for initializing a Git repository. Sure, it’ll run git init under the hood, but it’ll do more than just that. It will also create a remote repository on GitHub right from the command line, allow the user to interactively create a .gitignore file, and finally perform an initial commit and push.

As ever, the code accompanying this tutorial can be found on our GitHub repo.

Build a Node CLI

Why Build a Command-line Tool with Node.js?

Before we dive in and start building, it’s worth looking at why we might choose Node.js to build a command-line application.

The most obvious advantage is that, if you’re reading this, you’re probably already familiar with it — and, indeed, with JavaScript.

Another key advantage, as we’ll see as we go along, is that the strong Node.js ecosystem means that among the hundreds of thousands of packages available for all manner of purposes, there are a number which are specifically designed to help build powerful command-line tools.

Finally, we can use npm to manage any dependencies, rather than have to worry about OS-specific package managers such as Aptitude, Yum or Homebrew.

Tip: that isn’t necessarily true, in that your command-line tool may have other external dependencies.

What We’re Going to Build: ginit

Ginit, our Node CLI in action

For this tutorial, We’re going to create a command-line utility which I’m calling ginit. It’s git init, but on steroids.

You’re probably wondering what on earth that means.

As you no doubt already know, git init initializes a git repository in the current folder. However, that’s usually only one of a number of repetitive steps involved in the process of hooking up a new or existing project to Git. For example, as part of a typical workflow, you may well:

initialise the local repository by running git init create a remote repository, for example on GitHub or Bitbucket — typically by leaving the command line and firing up a web browser add the remote create a .gitignore file add your project files commit the initial set of files push up to the remote repository.

There are often more steps involved, but we’ll stick to those for the purposes of our app. Nevertheless, these steps are pretty repetitive. Wouldn’t it be better if we could do all this from the command line, with no copy-pasting of Git URLs and such like?

So what ginit will do is create a Git repository in the current folder, create a remote repository — we’ll be using GitHub for this — and then add it as a remote. Then it will provide a simple interactive “wizard” for creating a .gitignore file, add the contents of the folder and push it up to the remote repository. It might not save you hours, but it’ll remove some of the initial friction when starting a new project.

With that in mind, let’s get started.

The Application Dependencies

One thing is for certain: in terms of appearance, the console will never have the sophistication of a graphical user interface. Nevertheless, that doesn’t mean it has to be plain, ugly, monochrome text. You might be surprised by just how much you can do visually, while at the same time keeping it functional. We’ll be looking at a couple of libraries for enhancing the display: chalk for colorizing the output and clui to add some additional visual components. Just for fun, we’ll use figlet to create a fancy ASCII-based banner and we’ll also use clear to clear the console.

In terms of input and output, the low-level Readline Node.js module could be used to prompt the user and request input, and in simple cases is more than adequate. But we’re going to take advantage of a third-party package which adds a greater degree of sophistication — Inquirer. As well as providing a mechanism for asking questions, it also implements simple input controls: think radio buttons and checkboxes, but in the console.

We’ll also be using minimist to parse command-line arguments.

Here’s a complete list of the packages we’ll use specifically for developing on the command line:

chalk — colorizes the output clear — clears the terminal screen clui — draws command-line tables, gauges and spinners figlet — creates ASCII art from text inquirer — creates interactive command-line user interface minimist — parses argument options configstore — easily loads and saves config without you having to think about where and how.

Additionally, we’ll also be using the following:

@octokit/rest — a GitHub REST API client for Node.js lodash — a JavaScript utility library simple-git — a tool for running Git commands in a Node.js application touch — a tool for implementating the Unix touch command. Getting Started

Although we’re going to create the application from scratch, don’t forget that you can also grab a copy of the code from the repository which accompanies this article.

Create a new directory for the project. You don’t have to call it ginit, of course:

mkdir ginit cd ginit

Create a new package.json file:

npm init

Follow the simple wizard, for example:

name: (ginit) version: (1.0.0) description: "git init" on steroids entry point: (index.js) test command: git repository: keywords: Git CLI author: [YOUR NAME] license: (ISC)

Now install the dependencies:

npm install chalk clear clui figlet inquirer minimist configstore @octokit/rest lodash simple-git touch --save

Alternatively, simply copy-paste the following package.json file — modifying the author appropriately — or grab it from the repository which accompanies this article:

{ "name": "ginit", "version": "1.0.0", "description": "\"git init\" on steroids", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "Git", "CLI" ], "author": "Lukas White <hello@lukaswhite.com>", "license": "ISC", "bin": { "ginit": "./index.js" }, "dependencies": { "@octokit/rest": "^14.0.5", "chalk": "^2.3.0", "clear": "0.0.1", "clui": "^0.3.6", "configstore": "^3.1.1", "figlet": "^1.2.0", "inquirer": "^5.0.1", "lodash": "^4.17.4", "minimist": "^1.2.0", "simple-git": "^1.89.0", "touch": "^3.1.0" } }

Now create an index.js file in the same folder and require the following dependencies:

const chalk = require('chalk'); const clear = require('clear'); const figlet = require('figlet'); Adding Some Helper Methods

We’re going to create a lib folder where we’ll split our helper code into modules:

files.js — basic file management inquirer.js — command-line user interaction github.js — access token management repo.js — Git repository management.

Let’s start with lib/files.js. Here, we need to:

get the current directory (to get a default repo name) check whether a directory exists (to determine whether the current folder is already a Git repository by looking for a folder named .git).

This sounds straightforward, but there are a couple of gotchas to take into consideration.

Firstly, you might be tempted to use the fs module’s realpathSync method to get the current directory:

path.basename(path.dirname(fs.realpathSync(__filename)));

This will work when we’re calling the application from the same directory (e.g. using node index.js), but bear in mind that we’re going to be making our console application available globally. This means we’ll want the name of the directory we’re working in, not the directory where the application resides. For this purpose, it’s better to use process.cwd:

path.basename(process.cwd());

Secondly, the preferred method of checking whether a file or directory exists keeps changing.The current way is to use fs.stat or fs.statSync. These throw an error if there’s no file, so we need to use a try … catch block.

Finally, it’s worth noting that when you’re writing a command-line application, using the synchronous version of these sorts of methods is just fine.

Putting that all together, let’s create a utility package in lib/files.js:

const fs = require('fs'); const path = require('path'); module.exports = { getCurrentDirectoryBase : () => { return path.basename(process.cwd()); }, directoryExists : (filePath) => { try { return fs.statSync(filePath).isDirectory(); } catch (err) { return false; } } };

Go back to index.js and ensure you require the new file:

const files = require('./lib/files');

With this in place, we can start developing the application.

Initializing the Node CLI

Now let’s implement the start-up phase of our console application.

In order to demonstrate some of the packages we’ve installed to enhance the console output, let’s clear the screen and then display a banner:

clear(); console.log( chalk.yellow( figlet.textSync('Ginit', { horizontalLayout: 'full' }) ) );

The output from this is shown below.

The welcome banner on our Node CLI, created using Chalk and Figlet

Next up, let’s run a simple check to ensure that the current folder isn’t already a Git repository. That’s easy: we just check for the existence of a .git folder using the utility method we just created:

if (files.directoryExists('.git')) { console.log(chalk.red('Already a git repository!')); process.exit(); }

Tip: notice we’re using the chalk module to show a red-colored message.

The post Build a JavaScript Command Line Interface (CLI) with Node.js appeared first on SitePoint.

6 Popular Portfolio Builders for Designers

Oct 16, 2019

Description:

Popular Portfolio Builders for Designers

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

Doing a great job of showcasing your work doesn’t have to be difficult. You don’t have to print out a batch of fancy brochures to distribute or carry around a folder containing a sheaf of papers. You’ll get far better results by using a website builder to create your own personal online portfolio for the whole world to see.

Building a portfolio website is relatively easy if you have the right tool for the job. If you can envision an awesome, engaging portfolio, you can build it. Especially with any of the six portfolio website tools described in this article. Since all six are top-of-the-line tools, there’s no reason to settle for anything else.

Best of all, these website building tools are either free or offer free trials.

1. Portfoliobox

A screenshot of the Portfoliobox website

Portfoliobox was designed with photographers, artists, web designers, and other creative types in mind. Small business owners and entrepreneurs will find it attractive as well. This portfolio website builder is super easy to use, and since it’s not theme-based, it’s extremely flexible as well. Another plus is you don’t have to worry about coding.

As its name implies, this is a perfect tool for creating portfolio websites that range in style and looks from the epitome of professionalism to flat-out awesome. You can display your work or your products to the world, and by doing so you’ll hopefully earn a bushel of dollars, euros, or whatever, as well.

We suggest you try the free plan. In that way, you can get acquainted with Portfoliobox while having the tools at hand to create a medium-sized portfolio. If you have large galleries of images in mind, you may eventually want to upgrade to the pro plan. If you’re a student, opening a student account may be your best move.

Portfoliobox 4 is currently in the works and coming soon. Features include increased flexibility and functionality and a more intuitive interface. Portfoliobox has more than one million users.

2. Wix

Start creating your portfolio with Wix

Wix is a versatile and powerful website building tool you can use with great effect to promote your business or build an online shop. Where Wix really shines, however, is in the role of a portfolio website builder. Everything is drag and drop, supported by the necessary tools and features to customize any of the 500+ designer-made templates you choose to work with.

If you can visualize an online portfolio that’s truly stunning and a cut above the rest, you can build it — without coding. Rather than being restricted to trying to cleverly present a series of static images, you can use scroll effects, animations, video backgrounds and more to bring your portfolio to life and keep viewers engaged and encouraged to spread the word.

If you want total freedom to create your crowd-pleasing portfolio website, Wix is for you.

Weebly

Weebly screenshot

We said up front that you shouldn’t have to settle for less than the best, and that certainly applies to the Weebly portfolio website builder. What you design and build is limited only by your imagination, and if your technical expertise is somewhat challenged and you lack coding experience it doesn’t matter one bit. Everything you need is at your fingertips.

If “free” appeals to you, that’s just one more reason to go with Weebly. The website builder is free, hosting is free, and there’s even a mobile app you can use to manage your portfolio website and track its performance — from anywhere.

You can either purchase a domain from Weebly or use your own. If you need professional photos for your portfolio, Weebly can provide them at an affordable price.

4. Mobirise Website Builder

Mobirise screenshot

Since Mobirise is an offline website builder, you can download it and get started building an awesome portfolio website right away. No coding is necessary. Google AMP and Bootstrap 4 guarantees your website will be lightning-fast and 100% mobile friendly.

You’ll have plenty of trendy themes and templates to work with. Best of all, Mobirise is free for both personal and commercial uses — making it a very attractive option.

The post 6 Popular Portfolio Builders for Designers appeared first on SitePoint.

Go off Grid: Offline Reader for SitePoint Premium Now in Beta

Oct 15, 2019

Description:

We've done a massive amount of work on the SitePoint Premium experience this year, but users have been very clear about what they want to see next.

Our most requested feature is offline access to books in the SitePoint Premium library, and today, it's here.

We've been working on this for a long time and we're very excited to release what we think is a great way to read these books offline. But we hope you'll bear in mind that this is the first beta release of offline access, and we expect that there will be issues.

We're releasing this as an MVP to our Premium users so that we can iterate on it based on your feedback. This solution will allow you to read our content offline on any device, without having to download a specialized app.

You can now access this feature in the reader in SitePoint Premium. You will need to use a modern browser, as we're running service workers and indexDB to enable this feature.

Downloading a book is a two-stage process:

Click the download toggle as shown in the screenshot below, which will save the book to be accessed offline. You will then need to save the page, either natively in the browser or via a bookmark to be able to access the book while offline.

Please try it out and give us your feedback. There's a dedicated thread for feedback over on the SitePoint Community, which you can access with your existing SitePoint Premium account.

Keep your eye on this feature. We're working to release a new version soon, which will make it easier to see which titles you have downloaded for offline access.

Head to the library and test the offline reader Head over to our feedback thread

The post Go off Grid: Offline Reader for SitePoint Premium Now in Beta appeared first on SitePoint.

Getting Started with GraphQL and React Native

Oct 9, 2019

Description:

In 2012, Facebook engineer Nick Schrock started work on a small prototype to facilitate moving away from an old, unsupported partner API that powered the current Facebook News Feed. At the time, this was called “SuperGraph”. Fast forward to today and SuperGraph has helped shape the open-source query language GraphQL, which has been much of the buzzword in recent times.

Facebook describes GraphQL as a “query language for APIs and a runtime for fulfilling those queries with your existing data”. Put simply, GraphQL is an alternative to REST that has been steadily gaining popularity since its release. Whereas with REST a developer would usually collate data from a series of endpoint requests, GraphQL allows the developer to send a single query to the server that describes the exact data requirement.

Prerequisites

For this tutorial, you’ll need a basic knowledge of React Native and some familiarity with the Expo environment. You’ll also need the Expo client installed on your mobile device or a compatible simulator installed on your computer. Instructions on how to do this can be found here.

Project Overview

In this tutorial, we’re going to demostrate the power of GraphQL in a React Native setting by creating a simple coffee bean comparison app. So that you can focus on all of the great things GraphQL has to offer, I’ve put together the base template for the application using Expo.

A mockup of our coffee comparison app

To get started, you can clone this repo and navigate to the “getting-started” branch, which includes all of our basic views to start adding our GraphQL data to, as well as all of our initial dependencies, which at this stage are:

{ "expo": "^32.0.0", "react": "16.5.0", "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz", "react-navigation": "^3.6.1" }

To clone this branch, you’ll need to open up terminal and run this command:

git clone https://github.com/jamiemaison/graphql-coffee-comparison.git

To then navigate to the getting-started branch, you move into the newly cloned repo with cd graphql-coffee-comparison and run git checkout getting-started.

The next stage is to install our dependencies. To do this, make sure you’re on Node v11.10.1 and run npm install in the root directory of the project. This will add all of the dependencies listed above to your node_modules folder.

To start adding GraphQL to our React Native app, we’re going to need to install a few more dependencies that help us perform a few simple GraphQL functions. As is common with modern JavaScript development, you don’t need all of these dependencies to complete the data request, but they certainly help in giving the developer a better chance of structuring some clean, easy-to-read code. The dependencies you’ll need can be installed by running npm install --save apollo-boost react-apollo graphql-tag graphql.

Here’s an overview of what these dependencies are:

apollo-boost: a zero-configuration way of getting started with GraphQL in React/React Native react-apollo: this provides an integration between GraphQL and the Apollo client graphql-tag: a template literal tag that parses GraphQL queries graphql: the JavaScript reference implementation for GraphQL

Once all of the necessary dependencies have finished installing, run npm start. You should now see your familiar Expo window, and if you launch the app (either via a simulator or on a device) then you should see a screen similar to this:

A mockup of our getting started page

In basic terms, this application has two screens that are managed by react-navigation, Home.js and CoffeePage.js. The Home screen contains a simple FlatList that renders all of the coffee beans supplied to its data field. When clicked on, the user is navigated to the CoffeePage for that item, which displays more information about the product. It’s our job to now populate these views with interesting data from GraphQL.

The complete coffee page

Apollo Server Playground

There are two main elements to any successful GraphQL transaction: the server holding the data, and the front-end query making the request. For the purposes of this tutorial, we aren’t going to start delving into the wonderful world of server-side code, so I’ve created our server for us ready to go. All you need to do is navigate to yq42lj36m9.sse.codesandbox.io in your favorite browser and leave it running throughout the course of development. For those interested, the server itself is running using apollo-server and contains just enough code to hold the data we need and serve it upon receiving an appropriate query. For further reading, you can head over to apollographql.com to read more about apollo-server.

GraphQL Query Basics

Before we get into writing the actual code that’s going to request the data we need for our coffee bean comparison app, we should understand just how GraphQL queries work. If you already know how queries work or just want to get started with coding, you can skip ahead to the next section.

Note: these queries won’t work with our codesandbox server, but feel free to create your own at codesandbox.io if you’d like to test out the queries.

At its simplest level, we can use a flat structure for our queries when we know the shape of the data we’re requesting:

QUERY: RESPONSE: { { coffee { "coffee": { blend "blend": "rich" } } } }

On the left, we see the GraphQL query requesting the blend field from coffee. This works well when we know exactly what our data structure is, but what about when things are less transparent? In this example, blend returns us a string, but queries can be used to request objects as well:

QUERY: RESPONSE: { { coffee { "coffee": { beans { "beans": [ blend { } blend: "rich" } }, } { blend: "smooth" } ] } }

Here you can see we are simply requesting the beans object, with only the field blend being returned from that object. Each object in the beans array may very well contain other data other than blend, but GraphQL queries help us request only the data we need, cutting out any extra information that’s not necessary for our application.

So what about when we need to be more specific than this? GraphQL provides the capability for many things, but something that allows for extremely powerful data requests is the ability to pass arguments in your query. Take the following example:

QUERY: RESPONSE: { { coffee(companyId: "2") { "coffee": { beans { "beans": [ blend { } blend: "rich" } }, } { blend: "smooth" } ] } }

What we see is that we can pass an argument — in this case, the companyId — which ensures that we are only returned beans from one particular company. With REST, you can pass a single set of arguments via query params and URL segments, but with GraphQL querying every single field, it can get its own set of arguments. This allows GraphQL to be a dynamic solution for making multiple API fetches per request.

The post Getting Started with GraphQL and React Native appeared first on SitePoint.

macOS Catalina: 5 Things Web Developers & Designers Should Know

Oct 8, 2019

Description:

macOS Catalina is here and available for download, and you've no doubt heard all about the breakup of iTunes and the new consumer-oriented entertainment apps shipping with the system.

But what do developers, designers, and other tech professionals need to know? We run through the key points.

32-bit Support Ends with Catalina

Are you relying on some older, obscure native app for a specific function, as so many developers and designers do? Your Catalina update could throw you a wildcard: it's the first macOS release that drops support for 32-bit apps.

During the setup process, you'll be given a list of installed apps that will no longer open after the update. If you want to keep using that tool, it's time to hit up the developer for a long-overdue update... or stay on Mojave for a while longer yet.

A Cross-Platform Catalyst

Mojave brought iOS ports of the News, Stocks, Voice Memos and Home apps to macOS. In Catalina, Apple is opening the tools that enabled these ports up to developers under the name of Catalyst.

While this doesn't directly affect web development work, it does make iOS a more attractive native development platform, which may inform your future platform choices. And if Apple's plan to reinvigorate stale macOS third-party app development with some of the action from iOS works, you could incorporate better productivity and development apps into your workflow in the near future.

For now, Catalyst is available to developers of iPad apps — we expect that to broaden in the future.

Voice Control

Catalina offers accessibility improvements in the form of improved Voice Control for those who have difficulty seeing, or using keyboards and mice.

Of course, developers should ensure that their apps work as well as they can with this tool, because it's the right thing to do.

Developers are known for their love of keyboard shortcut mastery, but no doubt the ability to create custom commands has inspired determined lifehackers. What if you never had to take your cursor or eyes off of VS Code to run other frequent workflows?

We look forward to seeing what the community comes up with.

Screen Time

Do you waste too much time using your computer for mindless entertainment, forcing you to stay up late making up the time productively?

Or are you a workaholic who just can't find the will to shut off and disconnect?

If you're like most of us in the industry, you're a mix of the two. Catalina introduces a variant of the Screen Time app that's been on iOS for a couple of years now.

Screen Time for macOS provides you with visual analytics that help you understand the way you're spending time on your device, which can often lead to some unexpected epiphanies. It also lets you schedule downtime, forcing you off the computer and into the real world at the right time.

As with iOS, you can also set time limits for specific apps, and there are some ways to moderate your web content usage without outright blocking your web browser from opening.

Sidecar: The Most Expensive Secondary Display You'll Ever Own

For developers, designers, and all other web professionals, the real headline feature of Catalina is Sidecar. Sidecar turns your iPad into a secondary display for your Mac, and it's really easy to enable (provided you have the requisite tablet, which is not included with the operating system update).

The best reason to use Sidecar over a standard display is Apple Pencil integration. Designers will love the ability to draw directly on the screen when using Sketch and Illustrator without switching devices all the time. You can even mirror your Mac's screen if you'd like an unobstructed view of what you're sketching on one side.

Most of us will use Sidecar as a place to dump Slack or a terminal window, but in any case, it's clear it'll be the most beneficial update for many of us.

How'd You Go?

Let us know how you went with the upgrade, and what you've enjoyed most so far. We always recommend waiting a few days for the bugs to shake out — especially with Apple's recent track record — but initial reports suggest the release version is pretty solid after all.

The post macOS Catalina: 5 Things Web Developers & Designers Should Know appeared first on SitePoint.

9 of the Best Animation Libraries for UI Designers

Oct 8, 2019

Description:

This is the latest update to our guide to helping you choose the right animation library for each task. We're going to run-through 9 free, well-coded animation libraries best-suited to UI design work — covering their strengths and weaknesses, and when to choose each one.

Take your CSS animations to the next level with our Animating with CSS course by Donovan Hutchinson, the man behind CSS Animation Rocks.

Front-end web design has been through a revolution in the last decade. In the late naughties, most of us were still designing static magazine layouts. Nowadays, we're building “digital machines” with thousands of resizing, coordinated, moving parts.

Quite simply, great UI designers need to be great animators too — with a solid working understanding of web animation techniques.

Keep in mind that we're looking at each library from the perspective of a code-savvy UI designer, not as a “code guru” developer. Some of these libraries are pure CSS. Others are JavaScript, but none require anything more than basic HTML/CSS understanding to be useful. Link the library; add a CSS class.

Quite simply, great UI designers need to be great animators with a rock-solid understanding of the underlying tech.

This is the latest update to our guide to helping you choose the right animation library for each task. We're going to run-through 9 free, well-coded animation libraries best-suited to UI design work – their strengths and weaknesses and when to choose each one.

Some are pure CSS. Others are JavaScript, but none require anything more than basic HTML/CSS understanding to be used.

Enjoy.

The 2017 Top 9 Animation Libraries List Animate.css Bounce.js AnimeJS Magic Animations DynCSS CSShake Hover.CSS Velocity.js AniJS Animate.css

Animate.css is one of the smallest and most easy-to-use CSS animation libraries available. Applying the Animate library to your project is as simple as adding the required CSS classes to your HTML elements. You can also use jQuery to call the animations on a particular event.

Animate.css

Creators: Daniel Eden Released: 2013 Current Version: 3.5.2 Most Recent Update: April 2017 Popularity: 41,000+ stars on GitHub Description: "A cross-browser library of CSS animations. As easy to use as an easy thing." Library Size: 43 kB GitHub: https://github.com/daneden/animate.css License: MIT

As of mid-2017, it still one of the most popular and widely-used CSS animation libraries and its minified file is small enough (16.6kb) for inclusion in mobile websites as well. It has 41,000 stars on Github and is used as a component in many larger projects.

Animate.css is still under active development after 4 years. We feel that this is one of the simplest and most robust animation libraries and would definitely recommend you to use this in your next project.

Bounce.js

Bounce.js is a tool and javascript library that focusses on providing a selection of unique bouncy CSS animations to your website.

Bounce.js

This project is open-source with its code on GitHub.

Creators: Tictail Released: 2014 Current Version: 0.8.2 Most Recent Update: Feb 2015 Popularity: 4,967+ stars on GitHub Description: "Create beautiful CSS3 powered animations in no time." Library Size: 16 kB GitHub: https://github.com/tictail/bounce.js License: MIT

Bounce.js is a neat animation library shipped with about ten animation 'pre-sets' – hence the small size of the library. As with animate.css, the animations are smooth and flawless. You might want to consider using this library if your needs focus on 'pop and bubble' animation types and could benefit from a lower file size overhead.

AnimeJS

AnimeJS is described as a lightweight JavaScript animation library that 'works with any CSS Properties, individual CSS transforms, SVG or any DOM attributes, and JavaScript Objects'. It's pretty awesome – so awesome in fact, that the GIF capture I took below can't do justice to how smooth and buttery the motion is.

Bounce.js

This project is available on GitHub.

Creator: Julian Garnier Released: 2016 Current Version: 2.0.2 Most Recent Update: March 2017 Popularity: 12,222+ stars on GitHub Description: "JavaScript Animation Engine." Library Size: 10.9kB GitHub: https://github.com/juliangarnier/anime License: MIT

AnimeJS is only newcomer to our list but has won a lot of converts in the 12 months since it's creation. It's incredibly versatile and powerful and wouldn't be out of place being used within HTML games. The only real question is 'is it overkill for simple web apps'?

Maybe, but as its fast, small and relatively easy to learn, it's hard to find fault with it.

Magic Animations

Magic Animations has been one impressive animation libraries available. It has many different animations, many of which are quite unique to this library. As with Animate.css, you can implement Magic by simply importing the CSS file. You can also make use of the animations from jQuery. This project offers a particularly cool demo application.

Magic Animations

The post 9 of the Best Animation Libraries for UI Designers appeared first on SitePoint.

Create a Cron Job on AWS Lambda

Oct 3, 2019

Description:

Create a Cron Job on AWS Lambda

Cron jobs are really useful tools in any Linux or Unix-like operating systems. They allow us to schedule scripts to be executed periodically. Their flexibility makes them ideal for repetitive tasks like backups and system cleaning, but also data fetching and data processing.

For all the good things they offer, cron jobs also have some downsides. The main one is that you need a dedicated server or a computer that runs pretty much 24/7. Most of us don't have that luxury. For those of us who don't have access to a machine like that, AWS Lambda is the perfect solution.

AWS Lambda is an event-driven, serverless computing platform that's a part of the Amazon Web Services. It’s a computing service that runs code in response to events and automatically manages the computing resources required by that code. Not only is it available to run our jobs 24/7, but it also automatically allocates the resources needed for them.

Setting up a Lambda in AWS involves more than just implementing a couple of functions and hoping they run periodically. To get them up and running, several services need to be configured first and need to work together. In this tutorial, we'll first go through all the services we'll need to set up, and then we'll implement a cron job that will fetch some updated cryptocurrency prices.

Understanding the Basics

As we said earlier, some AWS services need to work together in order for our Lambda function to work as a cron job. Let's have a look at each one of them and understand their role in the infrastructure.

S3 Bucket

An Amazon S3 bucket is a public cloud storage resource available in Amazon Web Services' (AWS) Simple Storage Service (S3), an object storage offering. Amazon S3 buckets, which are similar to file folders, store objects, which consist of data and its descriptive metadata. — TechTarget

Every Lambda function needs to be prepared as a “deployment package”. The deployment package is a .zip file consisting of the code and any dependencies that code might need. That .zip file can then be uploaded via the web console or located in an S3 bucket.

IAM Role

An IAM role is an IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, in that it is an AWS identity with permission policies that determine what the identity can and cannot do in AWS. — Amazon

We’ll need to manage permissions for our Lambda function with IAM. At the very least it should be able to write logs, so it needs access to CloudWatch Logs. This is the bare minimum and we might need other permissions for our Lambda function. For more information, the AWS Lambda permissions page has all the information needed.

CloudWatch Events Rule

CloudWatch Events support cron-like expressions, which we can use to define how often an event is created. We'll also need to make sure that we add our Lambda function as a target for those events.

Lambda Permission

Creating the events and targeting the Lambda function isn’t enough. We'll also need to make sure that the events are allowed to invoke our Lambda function. Anything that wants to invoke a Lambda function needs to have explicit permission to do that.

These are the building blocks of our AWS Lambda cron job. Now that we have an idea of all the moving parts of our job, let's see how we can implement it on AWS.

Implementing a Cron Job on AWS

A lot of the interactions we described earlier are taken care of by Amazon automatically. In a nutshell, all we need to do is to implement our service (the actual lambda function) and add rules to it (how often and how the lambda will be executed). Both permissions and roles are taken care of by Amazon; the defaults provided by Amazon are the ones we'll be using.

Lambda function

First, let's start by implementing a very simple lambda function. In the AWS dashboard, use the Find Services function to search by lambda. In the lambda console, select Create a function. At this point, we should be in Lambda > Functions > reate Function.

To get things going, let's start with a static log message. Our service will only be a print function. For this, we'll use Node.js 10x as our runtime language. Give it a function name, and on Execution Role let's stay with Create a new role with basic lambda permissions. This is a basic set of permissions on IAM that will allow us to upload logs to Amazon CloudWatch logs. Click Create Function.

Create a new lambda function

Our function is now created with an IAM Role. In the code box, substitute the default code with the following:

exports.handler = async (event) => { console.log("Hello Sitepoint Reader!"); return {}; };

To check if the code is executing correctly, we can use the Test function. After giving a name to our test, it will execute the code and show its output in the Execution Result field just below our code.

If we test the code above we can see that we have no response, but in the function logs, we can see we have our message printed. This indicates that our service is running correctly so we can proceed with our cron implementation.

The post Create a Cron Job on AWS Lambda appeared first on SitePoint.

Cloning Tinder Using React Native Elements and Expo

Oct 1, 2019

Description:

Cloning Tinder Using React Native Elements and Expo

Making pixel-perfect layouts on mobile is hard. Even though React Native makes it easier than its native counterparts, it still requires a lot of work to get a mobile app to perfection.

In this tutorial, we’ll be cloning the most famous dating app, Tinder. We’ll then learn about a UI framework called React Native Elements, which makes styling React Native apps easy.

Since this is just going to be a layout tutorial, we’ll be using Expo, as it makes setting things up much easier than plain old react-native-cli. We’ll also be making use of a lot of dummy data to make our app.

We’ll be making a total of four screens—Home, Top Picks, Profile, and Messages.

Prerequisites

For this tutorial, you need a basic knowledge of React Native and some familiarity with Expo. You’ll also need the Expo client installed on your mobile device or a compatible simulator installed on your computer. Instructions on how to do this can be found here.

You also need to have a basic knowledge of styles in React Native. Styles in React Native are basically an abstraction similar to that of CSS, with just a few differences. You can get a list of all the properties in the styling cheatsheet.

Throughout the course of this tutorial we’ll be using yarn. If you don’t have yarn already installed, install it from here.

Also make sure you’ve already installed expo-cli on your computer.

If it’s not installed already, then go ahead and install it:

$ yarn global add expo-cli

To make sure we’re on the same page, these are the versions used in this tutorial:

Node 11.14.0 npm 6.4.1 yarn 1.15.2 expo 2.16.1

Make sure to update expo-cli if you haven’t updated in a while, since expo releases are quickly out of date.

We’re going to build something that looks like this:

Tinder Demo in Expo

If you just want to clone the repo, the whole code can be found on GitHub.

Getting Started

Let’s set up a new Expo project using expo-cli:

$ expo init expo-tinder

It will then ask you to choose a template. You should choose tabs and hit Enter.

Expo Init - Choose A Template

Then it will ask you to name the project. Type expo-tinder and hit Enter again.

Expo Init - Name the Project

Lastly, it will ask you to press y to install dependencies with yarn or n to install dependencies with npm. Press y.

Expo Init - Install the dependencies

This bootstraps a brand new React Native app using expo-cli.

React Native Elements

React Native Elements is a cross-platform UI Toolkit for React Native with consistent design across Android, iOS and Web.

It’s easy to use and completely built with JavaScript. It’s also the first UI kit ever made for React Native.

It allows us to fully customize styles of any of our components the way we want so every app has its own unique look and feel.

It’s also open source and backed by a community of awesome developers.

You can build beautiful applications easily.

React Native Elements Demo

Cloning Tinder UI

We’ve already created a project named expo-tinder.

To run the project, type this:

$ yarn start

Press i to run the iOS Simulator. This will automatically run the iOS Simulator even if it’s not opened.

Press a to run the Android Emulator. Note that the emulator must be installed and started already before typing a. Otherwise it will throw an error in the terminal.

It should look like this:

Expo Tabs App

The post Cloning Tinder Using React Native Elements and Expo appeared first on SitePoint.

How to Build a News App with Svelte

Sep 27, 2019

Description:

How to Build a News App with Svelte

Svelte is a new JavaScript UI library that's similar in many ways to modern UI libraries like React. One important difference is that it doesn't use the concept of a virtual DOM.

In this tutorial, we'll be introducing Svelte by building a news application inspired by the Daily Planet, a fictional newspaper from the Superman world.

About Svelte

Svelte makes use of a new approach to building users interfaces. Instead of doing the necessary work in the browser, Svelte shifts that work to a compile-time phase that happens on the development machine when you're building your app.

In a nutshell, this is how Svelte works (as stated in the official blog):

Svelte runs at build time, converting your components into highly efficient imperative code that surgically updates the DOM. As a result, you're able to write ambitious applications with excellent performance characteristics.

Svelte is faster than the most powerful frameworks (React, Vue and Angular) because it doesn't use a virtual DOM and surgically updates only the parts that change.

We'll be learning about the basic concepts like Svelte components and how to fetch and iterate over arrays of data. We'll also learn how to initialize a Svelte project, run a local development server and build the final bundle.

Prerequisites

You need to have a few prerequisites, so you can follow this tutorial comfortably, such as:

Familiarity with HTML, CSS, and JavaScript (ES6+), Node.js and npm installed on your development machine.

Node.js can be easily installed from the official website or you can also use NVM for easily installing and managing multiple versions of Node in your system.

We'll be using a JSON API as a source of the news for our app, so you need to get an API key by simply creating an account for free and taking note of your API key.

Getting Started

Now, let's start building our Daily Planet news application by using the degit tool for generating Svelte projects.

You can either install degit globally on your system or use the npx tool to execute it from npm. Open a new terminal and run the following command:

npx degit sveltejs/template dailyplanetnews

Next, navigate inside your project's folder and run the development server using the following commands:

cd dailyplanetnews npm run dev

Your dev server will be listening from the http://localhost:5000 address. If you do any changes, they'll be rebuilt and live-reloaded into your running app.

Open the main.js file of your project, and you should find the following code:

import App from './App.svelte'; const app = new App({ target: document.body, props: { name: 'world' } }); export default app;

This is where the Svelte app is bootstrapped by creating and exporting an instance of the root component, conventionally called App. The component takes an object with a target and props attributes.

The target contains the DOM element where the component will be mounted, and props contains the properties that we want to pass to the App component. In this case, it's just a name with the world value.

Open the App.svelte file, and you should find the following code:

<script> export let name; </script> <style> h1 { color: purple; } </style> <h1>Hello {name}!</h1>

This is the root component of our application. All the other components will be children of App.

Components in Svelte use the .svelte extension for source files, which contain all the JavaScript, styles and markup for a component.

The export let name; syntax creates a component prop called name. We use variable interpolation—{...}—to display the value passed via the name prop.

You can simply use plain old JavaScript, CSS, and HTML that you are familiar with to create Svelte components. Svelte also adds some template syntax to HTML for variable interpolation and looping through lists of data, etc.

Since this is a small app, we can simply implement the required functionality in the App component.

In the <script> tag, import the onMount() method from "svelte" and define the API_KEY, articles, and URL variables which will hold the news API key, the fetched news articles and the endpoint that provides data:

<script> export let name; import { onMount } from "svelte"; const API_KEY = "<YOUR_API_KEY_HERE>"; const URL = `https://newsapi.org/v2/everything?q=comics&sortBy=publishedAt&apiKey=${API_KEY}`; let articles = []; </script>

onMount is a lifecycle method. Here’s what the official tutorial says about that:

Every component has a lifecycle that starts when it is created and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle. The one you'll use most frequently is onMount, which runs after the component is first rendered to the DOM.

Next, let's use the fetch API to fetch data from the news endpoint and store the articles in the articles variable when the component is mounted in the DOM:

<script> // [...] onMount(async function() { const response = await fetch(URL); const json = await response.json(); articles = json["articles"]; }); </script>

Since the fetch() method returns a JavaScript Promise, we can use the async/await syntax to make the code look synchronous and eliminate callbacks.

The post How to Build a News App with Svelte appeared first on SitePoint.

Real-time Location Tracking with React Native and PubNub

Sep 25, 2019

Description:

Building a Real-time Location Tracking App with React Native and PubNub

With ever-increasing usage of mobile apps, geolocation and tracking functionality can be found in a majority of apps. Real-time geolocation tracking plays an important role in many on-demand services, such as these:

taxi services like Uber, Lyft or Ola food Delivery services like Uber Eats, Foodpanda or Zomato monitoring fleets of drones

In this guide, we’re going use React Native to create a real-time location tracking apps. We’ll build two React Native apps. One will act as a tracking app (called “Tracking app”) and the other will be the one that’s tracked (“Trackee app”).

Here’s what the final output for this tutorial will look like:

[video width="640" height="480" mp4="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2019/09/1569381508tracking.mp4"][/video]

Prerequisites

This tutorial requires a basic knowledge of React Native. To set up your development machine, follow the official guide here.

Apart from React Native, we’ll also be using PubNub, a third-party service that provides real-time data transfer and updates. We’ll use this service to update the user coordinates in real time.

Register for a free PubNub account here.

Since we’ll be using Google Maps on Android, we’ll also need a Google Maps API key, which you can obtain on the Google Maps Get API key page.

To make sure we’re on the same page, these are the versions used in this tutorial:

Node v10.15.0 npm 6.4.1 yarn 1.16.0 react-native 0.59.9 react-native-maps 0.24.2 pubnub-react 1.2.0 Getting Started

If you want to have a look at the source code of our Tracker and Trackee apps right away, here are their GitHub links:

Trackee App repo Tracker App repo

Let’s start with the Trackee app first.

Trackee App

To create a new project using react-native-cli, type this in the terminal:

$ react-native init trackeeApp $ cd trackeeApp

Now let’s get to the fun part — the coding.

Add React Native Maps

Since we’ll be using Maps in our app, we’ll need a library for this. We’ll use react-native-maps.

Install react-native-maps by following the installation instructions here.

Add PubNub

Apart from maps, we’ll also install the PubNub React SDK to transfer our data in real time:

$ yarn add pubnub-react

After that, you can now run the app:

$ react-native run-ios $ react-native run-android

You should see something like this on your simulator/emulator:

Trackee App

The post Real-time Location Tracking with React Native and PubNub appeared first on SitePoint.

How to Build Your First Telegram Chatbot with Node.js

Sep 18, 2019

Description:

So, this morning you woke up with the idea to develop a way to store and label interesting articles you've read. After playing with the idea, you figure a Telegram chatbot is the most convenient solution for this problem.

In this guide, we'll walk you through everything you need to know to build your first Telegram chatbot using JavaScript and Node.js.

To get started, we have to register our new bot with the so-called Botfather to receive our API access token.

Bot Registration with @BotFather

The first step towards our very own Telegram bot is registering the bot with the BotFather. The BotFather is a bot itself that makes your life much easier. It helps you with registering bots, changing the bot description, adding commands, and providing you with the API token for your bot.

The API token is the most important step, as this allows you to run the code that can perform tasks for the bot.

1. Finding the BotFather

The BotFather can be found on Telegram by searching for 'BotFather'. Click on the official BotFather, indicated with the white checkmark icon in the blue circle.

2. Registering a New Bot

Now we've found BotFather, let’s talk to him! You can start the conversation by typing /newbot. BotFather will ask you to choose a name for your both. This name can be anything and doesn’t have to be unique. To keep things simple, I named my bot ArticleBot.

Next, you will be prompted to input a username for the bot. The username must be unique and end in bot. Therefore, I chose michiel_article_bot, as that username was not yet taken. This will also be the username you use for looking up the bot in Telegram's search field.

FatherBot will return a success message with your token to access the Telegram HTTP API. Make sure to store this token safely, and certainly don't share it with anyone else.

3. Modifying the Bot

We can further modify the bot by adding a description or setting the commands we wish the bot to know. You can message the bot with the text /setcommands. It will show you how to input the commands with the format command1 - Description.

The post How to Build Your First Telegram Chatbot with Node.js appeared first on SitePoint.

How to Build Unique, Beautiful Websites with Tailwind CSS

Sep 13, 2019

Description:

Build Unique and Beautiful Web Sites with Tailwind CSS

When thinking about what CSS framework to use for a new project, options like Bootstrap and Foundation readily jump to mind. They’re tempting to use because of their ready-to-use, pre-designed components, which developers can use with ease right away. This approach works well with relatively simple websites with a common look and feel. But as soon as we start building more complex, unique sites with specific needs, a couple of problems arise.

At some point, we need to customize certain components, create new components, and make sure the final codebase is unified and easy to maintain after the changes.

It's hard to satisfy the above needs with frameworks like Bootstrap and Foundation, which give us a bunch of opinionated and, in many cases, unwanted styles. As a result, we have to continuously solve specificity issues while trying to override the default styles. It doesn't sound like a fun job, does it?

Ready-to-use solutions are easy to implement, but inflexible and confined to certain boundaries. On other hand, styling web sites without a CSS framework is powerful and flexible, but isn’t easy to manage and maintain. So, what’s the solution?

The solution, as always, is to follow the golden middle. We need to find and apply the right balance between the concrete and abstract. A low-level CSS framework offers such a balance. There are several frameworks of this kind, and in this tutorial, we'll explore the most popular one, Tailwind CSS.

What Is Tailwind?

Tailwind is more than a CSS framework, it's an engine for creating design systems. — Tailwind website

Tailwind is a collection of low-level utility classes. They can be used like lego bricks to build any kind of components. The collection covers the most important CSS properties, but it can be easily extended in a variety of ways. With Tailwind, customization isn’t pain in the neck anymore. The framework has great documentation, covering every class utility in detail and showing the ways it can be customized. All modern browsers, and IE11+, are supported.

Why Using Utility-first Framework?

A low-level, utility-first CSS framework like Tailwind has a plenty of benefits. Let's explore the most significant of them:

You have greater control over elements' appearance. We can change and fine-tune an element's appearance much more easily with utility classes. It's easy to manage and maintain in large projects, because you only maintain HTML files, instead of a large CSS codebase. It's easier to build unique, custom website designs without fighting with unwanted styles. It's highly customizable and extensible, which gives us unlimited flexibility. It has a mobile-first approach and easy implementation of responsive design patterns. There's the ability to extract common, repetitive patterns into custom, reusable components — in most cases without writing a single line of custom CSS. It has self-explanatory classes. We can imagine how the styled element looks only by reading the classes.

Finally, as Tailwind's creators say:

it's just about impossible to think this is a good idea the first time you see it — you have to actually try it.

So, let's try it!

Getting Started with Tailwind

To demonstrate Tailwind's customization features, we need to install it via npm:

npm install tailwindcss

The next step is to create a styles.css file, where we include the framework styles using the @tailwind directive:

@tailwind base; @tailwind components; @tailwind utilities;

After that, we run the npx tailwind init command, which creates a minimal tailwind.config.js file, where we'll put our customization options during the development. The generated file contains the following:

module.exports = { theme: {}, variants: {}, plugins: [], }

The next step is to build the styles in order to use them:

npx tailwind build styles.css -o output.css

Finally, we link the generated output.css file and Font Awesome in our HTML:

<link rel="stylesheet" type="text/css" href="output.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css">

And now, we’re ready to start creating.

Building a One-page Website Template

In the rest of the tutorial, we'll build a one-page website template using the power and flexibility of Tailwind's utility classes.

Here you can see the template in action.

I'm not going to explain every single utility (which would be boring and tiresome) so I suggest you to use the Tailwind cheatsheet as a quick reference. It contains all available utilities with their effect, plus direct links to the documentation.

We'll build the template section by section. They are Header, Services, Projects, Team, and Footer.

We firstly wrap all section in a container:

<div class="container mx-auto"> <!-- Put the sections here --> </div> Header (Logo, Navigation)

The first section — Header — will contain a logo on the left side and navigation links on the right side. Here’s how it will look:

The site header

Now, let's explore the code behind it.

<div class="flex justify-between items-center py-4 bg-blue-900"> <div class="flex-shrink-0 ml-10 cursor-pointer"> <i class="fas fa-drafting-compass fa-2x text-orange-500"></i> <span class="ml-1 text-3xl text-blue-200 font-semibold">WebCraft</span> </div> <i class="fas fa-bars fa-2x visible md:invisible mr-10 md:mr-0 text-blue-200 cursor-pointer"></i> <ul class="hidden md:flex overflow-x-hidden mr-10 font-semibold"> <li class="mr-6 p-1 border-b-2 border-orange-500"> <a class="text-blue-200 cursor-default" href="#">Home</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Services</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Projects</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Team</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">About</a> </li> <li class="mr-6 p-1"> <a class="text-white hover:text-blue-300" href="#">Contacts</a> </li> </ul> </div>

As you can see, the classes are pretty self-explanatory as I mentioned above. We'll explore only the highlights.

First, we create a flex container and center its items horizontally and vertically. We also add some top and bottom padding, which Tailwind combines in a single py utility. As you may guess, there’s also a px variant for left and right. We'll see that this type of shorthand is broadly used in many of the other utilities. As a background color, we use the darkest blue (bg-blue-900) from Tailwind's color palette. The palette contains several colors with shades for each color distributed from 100 to 900. For example, blue-100, blue-200, blue-300, etc.

In Tailwind, we apply a color to a property by specifying the property followed by the color and the shade number. For example, text-white, bg-gray-800, border-red-500. Easy peasy.

For the logo on the left side, we use a div element, which we set not to shrink (flex-shrink-0) and move it a bit away from the edge by applying the margin-left property (ml-10). Next we use a Font Awesome icon whose classes perfectly blend with those of Tailwind. We use one of them to make the icon orange. For the textual part of the logo, we use big, light blue, semi-bolded text, with a small offset to the right.

In the middle, we add an icon that will be visible only on mobile. Here we use one of the responsive breakpoint prefixes (md). Tailwind, like Bootstrap and Foundation, follows the mobile-first approach. This means that when we use utilities without prefix (visible), they apply all the way from the smallest to the largest devices. If we want different styling for different devices, we need to use the breakpoint prefixes. So, in our case the icon will be visible on small devices, and invisible (md:invisible) on medium and beyond.

At the right side we put the nav links. We style the Home link differently, showing that it’s the active link. We also move the navigation from the edge and set it to be hidden on overflow (overflow-x-hidden). The navigation will be hidden (hidden) on mobile and set to flex (md:flex) on medium and beyond.

You can read more about responsiveness in the documentation.

Services

Let's now create the next section, Services. Here’s how it will look:

The Services section

And here’s the code:

<div class="w-full p-6 bg-blue-100"> <div class="w-48 mx-auto pt-6 border-b-2 border-orange-500 text-center text-2xl text-blue-700">OUR SERVICES</div> <div class="p-2 text-center text-lg text-gray-700">We offer the best web development solutions.</div> <div class="flex justify-center flex-wrap p-10"> <div class="relative w-48 h-64 m-5 bg-white shadow-lg"> <div class="flex items-center w-48 h-20 bg-orange-500"> <i class="fas fa-bezier-curve fa-3x mx-auto text-white"></i> </div> <p class="mx-2 py-2 border-b-2 text-center text-gray-700 font-semibold uppercase">UI Design</p> <p class="p-2 text-sm text-gray-700">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac est massa.</p> <div class="absolute right-0 bottom-0 w-8 h-8 bg-gray-300 hover:bg-orange-300 text-center cursor-pointer"> <i class="fas fa-chevron-right mt-2 text-orange-500"></i> </div> </div> ... </div> </div>

We create a section with light blue background. Then we add an underlined title and a subtitle.

Next, we use a flex container for the services items. We use flex-wrap so the items will wrap on resize. We set the dimensions for each card and add some space and a drop shadow. Each card has a colored section with a topic icon, a title, and a description. And we also put a button with an icon in the bottom-right corner.

Here we use one of the pseudo-class variants (hover, focus, etc.). They’re used in the same way as responsive breakpoints. We use the pseudo-class prefix, followed by a colon and the property name (hover:bg-orange-300).

You can learn more about pseudo-class variants in the documentation.

For brevity, I show the code only for the first card. The other ones are similar. You have to change only the colors, icons, and titles. See the final HTML file on GitHub repo for a reference.

The post How to Build Unique, Beautiful Websites with Tailwind CSS appeared first on SitePoint.

How to Automatically Optimize Responsive Images in Gatsby

Sep 11, 2019

Description:

Image optimization — at least in my experience — has always been a major pain when building speedy websites. Balancing image quality and bandwidth efficiency is a tough act without the right tools. Photo editing tools such as Photoshop are great for retouching, cropping and resizing bitmap images. Unfortunately, they are not that good at creating 100% optimized images for the web.

Luckily, we have extension packages for build tools that can optimize images for us quickly:

Gulp: gulp-imagemin Grunt: grunt-imagemin Webpack: imagemin-webpack Parcel: parcel-plugin-imagemin

Unfortunately, image optimization alone is not enough. You need to make sure that the entire website is responsive and looks great at all screen sizes. This can easily be done through CSS, but here lies the problem:

Should you optimize your image for large screens or small screens?

If the majority of your audience is using mobile devices to access your site, then the logical choice is to optimize images for small screens. However, it's likely that a significant source of revenue is coming from visitors with large screens over 17". You definitely wouldn't want to neglect them.

Luckily, we have technology that allows us to deliver optimized responsive images for different screen sizes. This means we need to generate multiple optimized images with different resolutions fit for specific screen sizes or responsive breakpoints.

For WordPress site owners, this kind of image optimization requires the use of a plugin and a third-party service. The creation of these responsive images cannot be done on the hosting server without significantly slowing down the site for users, hence the need for a third-party service.

If you are using Gatsby to run your website, then you are in luck. This feature is built-in and already configured for you to optimize your responsive images. You just need to drop in some images and write a bit of code to link up your responsive images with your web page. When you run the gatsby build command, the images are optimized for you. This saves you from requiring a third-party service to perform the optimization for you. It's simply done on your deployment machine.

In the subsequent sections, we are going to learn:

How image optimization works in Gatsby How to optimize images on a web page How to optimize images in a Markdown post Prerequisites

Before we start, I would like to note that this tutorial is for developers who are just starting with Gatsby and would like to learn specifically about how to handle images. I am going to assume you already have a good foundation in the following topics:

The post How to Automatically Optimize Responsive Images in Gatsby appeared first on SitePoint.

Create an Offline-first React Native App Using WatermelonDB

Sep 10, 2019

Description:

React Native has different database storage mechanisms for different mobile app purposes. Simple structures — such as user settings, app settings, and other key-value pair data — can be handled easily using async storage or secure storage.

Other applications — such as Twitter clones — fetch data from the server and directly show it to the user. They maintain a cache of data, and if a user needs to interact with any document, they call the APIs directly.

So not all the applications require a database.

When We Need a Database

Applications such as the Nozbe (a to-do app), Expense (a tracker), and SplitWise (for in-app purchases), need to work offline. And to do so, they need a way to store data locally and sync it up with the server. This type of application is called an offline first app. Over time, these apps collect a lot of data, and it becomes harder to manage that data directly — so a database is needed to manage it efficiently.

Options in React Native

When developing an app, choose the database that best fits your requirements. If two options are available, then go with the one that has better documentation and quicker response to issues. Below are some of the best known options available for React Native:

WatermelonDB: an open-source reactive database that can be used with any underlying database. By default, it uses SQLite as the underlying database in React Native. SQLite (React Native, Expo): the oldest, most used, battle-tested and well-known solution. It’s available for most of the platforms, so if you’ve developed an application in another mobile app development framework, you might already be familiar with it. Realm (React Native): an open-source solution, but it also has an enterprise edition with lots of other features. They have done a great job and many well-known companies use it. FireBase (React Native, Expo): a Google service specifically for the mobile development platform. It offers lots of functionality, storage being just one of them. But it does require you to stay within their ecosystem to utilize it. RxDB: a real-time database for the Web. It has good documentation, a good rating on GitHub (> 9K stars), and is also reactive. Prerequisites

I assume you have knowledge about basic React Native and its build process. We’re going to use react-native-cli to create our application.

I’d also suggest setting up an Android or iOS development environment while setting up the project, as you may face many issues, and the first step in debugging is keeping the IDE (Android Studio or Xcode) opened to see the logs.

Note: you can check out the official guide for installing dependencies here for more information. As the official guidelines are very concise and clear, we won’t be covering that topic here.

To set up a virtual device or physical device, follow these guides:

using a physical device using a virtual device

Note: there’s a more JavaScript-friendly toolchain named Expo. The React Native community has also started promoting it, but I haven’t come across a large-scale, production-ready application that uses Expo yet, and Expo port isn’t currently available for those using a database such as Realm — or in our case, WatermelonDB.

App Requirements

We’ll create a movie search application with a title, poster image, genre, and release date. Each movie will have many reviews.

The application will have three screens.

Home will show two buttons — one to generate dummy records, and a second to add new movie. Below it, there will be one search input that can be used to query movie titles from the database. It will show the list of movies below the search bar. If any name is searched, the list will only show the searched movies.

home screen view

Clicking on any movie will open a Movie Dashboard, from where all its reviews can be checked. A movie can be edited or deleted, or a new review can be added from this screen.

movie dashboard

The third screen will be Movie Form, which is used to create/update a movie.

movie form

The source code is available on GitHub.

Why We Chose WatermelonDB (features)

We need to create an offline-first application, so a database is a must.

Features of WatermelonDB

Let’s look at some of the features of WatermelonDB.

Fully observable
A great feature of WatermelonDB is its reactive nature. Any object can be observed using observables, and it will automatically rerender our components whenever the data changes. We don’t have to make any extra efforts to use WatermelonDB. We wrap the simple React components and enhance them to make them reactive. In my experience, it just works seamlessly, and we don’t have to care about anything else. We make the changes in the object and our job’s done! It’s persisted and updated at all the places in the application.

SQLite under the hood for React Native
In a modern browser, just-in-time compilation is used to improve speed, but it’s not available in mobile devices. Also, the hardware in mobile devices is slower than in computers. Due to all these factors, JavaScript apps run slower in a mobile application. To overcome this, WatermelonDB doesn’t fetch anything until it’s needed. It uses lazy loading and SQLite as an underlying database on a separate thread to provide a fast response.

Sync primitives and sync adapter
Although WatermelonDB is just a local database, it also provides sync primitives and sync adapters. It makes it pretty easy to use with any of our own back-end databases. We just need to conform to the WatermelonDB sync protocol on the back end and provide the endpoints.

Further features include:

Statically typed using Flow Available for all platforms Dev Env and WatermelonDB Setup (v0.0)

We’re going to use react-native-cli to create our application.

Note: you may be able to use it with ExpoKit or Ejecting from Expo.

If you want to skip this part then clone the source repo and checkout the v0.0 branch.

Start a new project:

react-native init MovieDirectory cd MovieDirectory

Install dependencies:

npm i @nozbe/watermelondb @nozbe/with-observables react-navigation react-native-gesture-handler react-native-fullwidth-image native-base rambdax

Below is the list of installed dependencies and their uses:

native-base: a UI library that will be used for look and feel of our app. react-native-fullwidth-image: for showing full-screen responsive images. (Sometimes it can be a pain to calculate the width, height and also maintain aspect ratio. So it’s better to use an existing community solution.) @nozbe/watermelondb: the database we’ll be using. @nozbe/with-observables: contains the decorators (@) that will be used in our models. react-navigation: used for Managing routes/screens react-native-gesture-handler: the dependency for react-navigation. rambdax: used to generate a random number while creating dummy data.

Open your package.json and replace the scripts with the following code:

"scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "start:ios": "react-native run-ios", "start:android": "react-native run-android", "test": "jest" }

This will be used to run our application in the respective device.

Set Up WatermelonDB

We need to add a Babel plugin to convert our decorators, so install it as a dev dependency:

npm install -D @babel/plugin-proposal-decorators

Create a new file .babelrc in the root of the project:

// .babelrc { "presets": ["module:metro-react-native-babel-preset"], "plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]] }

Now use the following guides for your target environment:

iOS Android

Open the android folder in Android Studio and sync the project. Otherwise, it will give you an error when running the application for the first time. Do the same if you’re targeting iOS.

Before we run the application, we need to link the react-native-gesture handler package, a dependency of react-navigation, and react-native-vector-icons, a dependency of native-base. By default, to keep the binary size of the application small, React Native doesn’t contain all the code to support native features. So whenever we need to use a particular feature, we can use the link command to add the native dependencies. So let’s link our dependencies:

react-native link react-native-gesture-handler react-native link react-native-vector-icons

Run the application:

npm run start:android # or npm run start:ios

If you get an error for missing dependencies, run npm i.

The code up to here is available under the v0.0 branch.

version 0

Tutorial

As we’ll be creating a database application, a lot of the code will be back-end only, and we won’t be able to see much on the front end. It might seem a long, but have patience and follow the tutorial till the end. You won’t regret it!

The WatermelonDB workflow can be categorized into three main parts:

Schema: used to define the database table schema. Models: the ORM mapped object. We’ll interact with these throughout our application. Actions: used to perform various CRUD operations on our object/row. We can directly perform an action using a database object or we can define functions in our model to perform these actions. Defining them in models is the better practice, and we’re going to use that only.

Let’s get started with our application.

Initialize DB Schema and WatermelonDB (v0.1)

We’ll define our schema, models and database object in our application. We won’t able to see much in the application, but this is the most important step. Here we’ll check that our application works correctly after defining everything. If anything goes wrong, it will be easy to debug it at this stage.

Project Structure

Create a new src folder in the root. This will be the root folder for all of our React Native code. The models folder is used for all of our database-related files. It will behave as our DAO (Data Access Object) folder. This is a term used for an interface to some type of database or other persistence mechanism. The components folder will have all of our React components. The screens folder will have all the screens of our application.

mkdir src && cd src mkdir models mkdir components mkdir screens Schema

Go to the models folder, create a new file schema.js, and use the following code:

// schema.js import { appSchema, tableSchema } from "@nozbe/watermelondb"; export const mySchema = appSchema({ version: 2, tables: [ tableSchema({ name: "movies", columns: [ { name: "title", type: "string" }, { name: "poster_image", type: "string" }, { name: "genre", type: "string" }, { name: "description", type: "string" }, { name: "release_date_at", type: "number" } ] }), tableSchema({ name: "reviews", columns: [ { name: "body", type: "string" }, { name: "movie_id", type: "string", isIndexed: true } ] }) ] });

We’ve defined two tables — one for movies, and another for its reviews. The code itself self-explanatory. Both tables have related columns.

Note that, as per WatermelonDB’s naming convention, all the IDs end with an _id suffix, and the date field ends with the _at suffix.

isIndexed is used to add an index to a column. Indexing makes querying by a column faster, at the slight expense of create/update speed and database size. We’ll be querying all the reviews by movie_id, so we should mark it as indexed. If you want to make frequent queries on any boolean column, you should index it as well. However, you should never index date (_at) columns.

Models

Create a new file models/Movie.js and paste in this code:

// models/Movie.js import { Model } from "@nozbe/watermelondb"; import { field, date, children } from "@nozbe/watermelondb/decorators"; export default class Movie extends Model { static table = "movies"; static associations = { reviews: { type: "has_many", foreignKey: "movie_id" } }; @field("title") title; @field("poster_image") posterImage; @field("genre") genre; @field("description") description; @date("release_date_at") releaseDateAt; @children("reviews") reviews; }

Here we’ve mapped each column of the movies table with each variable. Note how we’ve mapped reviews with a movie. We’ve defined it in associations and also used @children instead of @field. Each review will have a movie_id foreign key. These review foreign key values are matched with id in the movie table to link the reviews model to the movie model.

For date also, we need to use the @date decorator so that WatermelonDB will give us the Date object instead of a simple number.

Now create a new file models/Review.js. This will be used to map each review of a movie.

// models/Review.js import { Model } from "@nozbe/watermelondb"; import { field, relation } from "@nozbe/watermelondb/decorators"; export default class Review extends Model { static table = "reviews"; static associations = { movie: { type: "belongs_to", key: "movie_id" } }; @field("body") body; @relation("movies", "movie_id") movie; }

We have created all of our required models. We can directly use them to initialize our database, but if we want to add a new model, we again have to make a change where we initialize the database. So to overcome this, create a new file models/index.js and add the following code:

// models/index.js import Movie from "./Movie"; import Review from "./Review"; export const dbModels = [Movie, Review];

Thus we only have to make changes in our models folder. This makes our DAO folder more organized.

Initialize the Database

Now to use our schema and models to initialize our database, open index.js, which should be in the root of our application. Add the code below:

// index.js import { AppRegistry } from "react-native"; import App from "./App"; import { name as appName } from "./app.json"; import { Database } from "@nozbe/watermelondb"; import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite"; import { mySchema } from "./src/models/schema"; import { dbModels } from "./src/models/index.js"; // First, create the adapter to the underlying database: const adapter = new SQLiteAdapter({ dbName: "WatermelonDemo", schema: mySchema }); // Then, make a Watermelon database from it! const database = new Database({ adapter, modelClasses: dbModels }); AppRegistry.registerComponent(appName, () => App);

We create an adapter using our schema for the underlying database. Then we pass this adapter and our dbModels to create a new database instance.

It’s better at this point in time to check whether our application is working fine or not. So run your application and check:

npm run start:android # or npm run start:ios

We haven’t made any changes in the UI, so the screen will look similar to before if everything worked out.

All the code up to this part is under the v0.1 branch.

The post Create an Offline-first React Native App Using WatermelonDB appeared first on SitePoint.

SitePoint Premium New Releases: Design Systems, SVG & React Native

Sep 6, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Design Systems and Living Styleguides

Create structured, efficient and consistent designs with design systems and styleguides. Explore materials, typography, vertical rhythm, color, icons and more.

➤ Read Design Systems and Living Styleguides.

Build a Real-time Location Tracking App with React Native and PubNub

In this guide, we’re going to use React Native to create real-time location tracking apps. We’ll build two React Native apps — a tracking app and one that’s tracked.

➤ Read Build a Real-time Location Tracking App with React Native and PubNub.

Practical SVG

From software basics to build tools to optimization, you’ll learn techniques for a solid workflow.

Go deeper: create icon systems, explore sizing and animation, and understand when and how to implement fallbacks. Get your images up to speed and look sharp!

➤ Read Practical SVG.

Create an Offline-first React Native App Using WatermelonDB

In this tutorial we’ll create an offline-first movie search application with a title, poster image, genre, and release date. Each movie will have many reviews. We'll use WatermelonDB to provide the database functionality for our app.

➤ Read Create an Offline-first React Native App Using WatermelonDB.

And More to Come…

We're releasing new content on SitePoint Premium regularly, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Design Systems, SVG & React Native appeared first on SitePoint.

Build a Real-time Voting App with Pusher, Node and Bootstrap

Sep 4, 2019

Description:

In this article, I'll walk you through building a full-stack, real-time Harry Potter house voting web application.

Real-time apps usually use WebSockets, a relatively new type of transfer protocol, as opposed to HTTP, which is a single-way communication that happens only when the user requests it. WebSockets allow for persistent communication between the server and the user, and all those users connected with the application, as long as the connection is kept open.

A real-time web application is one where information is transmitted (almost) instantaneously between users and the server (and, by extension, between users and other users). This is in contrast with traditional web apps where the client has to ask for information from the server. — Quora

Our Harry Potter voting web app will show options (all the four houses) and a chart on the right side that updates itself when a connected user votes.

To give you a brief idea of look and feel, the final application is going to look like this:

Harry Potter with Chart JS

Here's a small preview of how the real-time application works:

To make our application real-time, we’re going to use Pusher and WebSockets. Pusher sits as a real-time layer between your servers and your clients. It maintains persistent connections to the clients — over a WebSocket if possible, and falling back to HTTP-based connectivity — so that, as soon as your servers have new data to push to the clients, they can do so instantly via Pusher.

Building our Application

Let’s create our fresh application using the command npm init. You’ll be interactively asked a few questions on the details of your application. Here's what I had:

praveen@praveen.science ➜ Harry-Potter-Pusher $ npm init { "name": "harry-potter-pusher", "version": "1.0.0", "description": "A real-time voting application using Harry Potter's house selection for my article for Pusher.", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/praveenscience/Harry-Potter-Pusher.git" }, "keywords": [ "Harry_Potter", "Pusher", "Voting", "Real_Time", "Web_Application" ], "author": "Praveen Kumar Purushothaman", "license": "ISC", "bugs": { "url": "https://github.com/praveenscience/Harry-Potter-Pusher/issues" }, "homepage": "https://github.com/praveenscience/Harry-Potter-Pusher#readme" } Is this OK? (yes)

So, I left most settings with default values. Now it's time to install dependencies.

Installing Dependencies

We need Express, body-parser, Cross Origin Resource Sharing (CORS), Mongoose and Pusher installed as dependencies. To install everything in a single command, use the following. You can also have a glance of what this command outputs.

praveen@praveen.science ➜ Harry-Potter-Pusher $ npm i express body-parser cors pusher mongoose npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself. + pusher@2.1.2 + body-parser@1.18.3 + mongoose@5.2.6 + cors@2.8.4 + express@4.16.3 added 264 packages in 40.000s Requiring Our Modules

Since this is an Express application, we need to include express() as the first thing. While doing it, we also need some accompanying modules. So, initially, let’s start with this:

const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const cors = require("cors"); Creating the Express App

Let’s start with building our Express application now. To start with, we need to get the returned object of the express() function assigned to a new variable app:

const app = express(); Serving Static Assets

Adding the above line after the initial set of includes will initialize our app as an Express application. The next thing we need to do is to set up the static resources. Let’s create a new directory in our current project called public and let’s use Express's static middleware to serve the static files. Inside the directory, let’s create a simple index.html file that says “Hello, World”:

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>Hello, World</title> </head> <body> Hello, World! </body> </html>

To serve the static files, we have a built-in .use() function with express.static() in Express. The syntax is as follows:

app.use( express.static( path.join(__dirname, "public") ) );

We also need to use the body parser middleware for getting the HTTP POST content as JSON to access within the req.body. We'll also use urlencoded to get the middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings:

app.use( bodyParser.json() ); app.use( bodyParser.urlencoded( { extended: false } ) );

To allow cross-domain requests, we need to enable CORS. Let’s enable the CORS module by using the following code:

app.use( cors() );

Now all the initial configuration has been set. All we need to do now is to set a port and listen to the incoming connections on the specific port:

const port = 3000; app.listen(port, () => { console.log(`Server started on port ${port}.`); });

Make sure your final app.js looks like this:

const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const cors = require("cors"); // Create an App. const app = express(); // Serve the static files from public. app.use( express.static( path.join(__dirname, "public") ) ); // Include the body-parser middleware. app.use( bodyParser.json() ); app.use( bodyParser.urlencoded( { extended: false } ) ); // Enable CORS. app.use( cors() ); // Set the port. const port = 3000; // Listen to incoming connections. app.listen(port, () => { console.log(`Server started on port ${port}.`); });

Run the command to start the server:

$ npm run dev

Open your http://localhost:3000/ on a new tab and see the magic. You should be seeing a new page with “Hello, World”.

Preview of Hello World in Browser

The post Build a Real-time Voting App with Pusher, Node and Bootstrap appeared first on SitePoint.

State Management in React Native

Sep 3, 2019

Description:

State Management in React Native

Managing state is one of the most difficult concepts to grasp while learning React Native, as there are so many ways to do it. There are countless state management libraries on the npm registry — such as Redux — and there are endless libraries built on top of other state management libraries to simplify the original library itself — like Redux Easy. Every week, a new state management library is introduced in React, but the base concepts of maintaining the application state has remained the same since the introduction of React.

The most common way to set state in React Native is by using React’s setState() method. We also have the Context API to avoid prop drilling and pass the state down many levels without passing it to individual children in the tree.

Recently, Hooks have emerged into React at v16.8.0, which is a new pattern to simplify use of state in React. React Native got it in v0.59.

In this tutorial, we’ll learn about what state actually is, and about the setState() method, the Context API and React Hooks. This is the foundation of setting state in React Native. All the libraries are made on top of the above base concepts. So once you know these concepts, understanding a library or creating your own state management library will be easy.

What Is a State?

Anything that changes over time is known as state. If we had a Counter app, the state would be the counter itself. If we had a to-do app, the list of to-dos would change over time, so this list would be the state. Even an input element is in a sense a state, as it over time as the user types into it.

Intro to setState

Now that we know what state is, let’s understand how React stores it.

Consider a simple counter app:

import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => {}} title="Increment" /> <Button onPress={() => {}} title="Decrement" /> </> ) } }

In this app, we store our state inside the constructor in an object and assign it to this.state.

Remember, state can only be an object. You can’t directly store a number. That’s why we created a counter variable inside an object.

In the render method, we destructure the counter property from this.state and render it inside an h1. Note that currently it will only show a static value (0).

You can also write your state outside of the constructor as follows:

import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => {}} title="Increment" /> <Button onPress={() => {}} title="Decrement" /> </> ) } }

Now let’s suppose we want the + and - button to work. We must write some code inside their respective onPress handlers:

import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => { this.setState({ counter: counter + 1 }) }} title="Increment" /> <Button onPress={() => { this.setState({ counter: counter - 1 }) }} title="Decrement" /> </> ) } }

Now when we click the + and - buttons, React re-renders the component. This is because the setState() method was used.

The setState() method re-renders the part of the tree that has changed. In this case, it re-renders the h1.

So if we click on +, it increments the counter by 1. If we click on -, it decrements the counter by 1.

Remember that you can’t change the state directly by changing this.state; doing this.state = counter + 1 won’t work.

Also, state changes are asynchronous operations, which means if you read this.state immediately after calling this.setState, it won’t reflect recent changes.

This is where we use “function as a callback” syntax for setState(), as follows:

import React from 'react' import { Text, Button } from 'react-native' class Counter extends React.Component { state = { counter: 0 } render() { const { counter } = this.state return ( <> <Text>{counter}</Text> <Button onPress={() => { this.setState(prevState => ({ counter: prevState.counter + 1 })) }} title="Increment" /> <Button onPress={() => { this.setState(prevState => ({ counter: prevState.counter - 1 })) }} title="Decrement" /> </> ) } }

The “function as a callback” syntax provides the recent state — in this case prevState — as a parameter to setState() method.

This way we get the recent changes to state.

What are Hooks?

Hooks are a new addition to React v16.8. Earlier, you could only use state by making a class component. You couldn’t use state in a functional component itself.

With the addition of Hooks, you can use state in functional component itself.

Let’s convert our above Counter class component to a Counter functional component and use React Hooks:

import React from 'react' import { Text, Button } from 'react-native' const Counter = () => { const [ counter, setCounter ] = React.useState(0) return ( <> <Text>{counter}</Text> <Button onPress={() => { setCounter(counter + 1 ) }} title="Increment" /> <Button onPress={() => { setCounter(counter - 1 ) }} title="Decrement" /> </> ) }

Notice that we’ve reduced our Class component from 18 to just 12 lines of code. Also, the code is much easier to read.

Let’s review the above code. Firstly, we use React’s built-in useState method. useState can be of any type — like a number, a string, an array, a boolean, an object, or any type of data — unlike setState(), which can only have an object.

In our counter example, it takes a number and returns an array with two values.

The first value in the array is the current state value. So counter is 0 currently.

The second value in the array is the function that lets you update the state value.

In our onPress, we can then update counter using setCounter directly.

Thus our increment function becomes setCounter(counter + 1 ) and our decrement function becomes setCounter(counter - 1).

React has many built-in Hooks, like useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect and useDebugValue — which you can find more info about in the React Hooks docs.

Additionally, we can build our own Custom Hooks.

There are two rules to follow when building or using Hooks:

Only Call Hooks at the Top Level. Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Only Call Hooks from React Functions. Don’t call Hooks from regular JavaScript functions. Instead, you can either call Hooks from React functional components or call Hooks from custom Hooks.

By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.

Hooks are really simple to understand, and they’re helpful when adding state to a functional component.

The post State Management in React Native appeared first on SitePoint.

How to Redesign Unsplash Using Styled Components

Aug 29, 2019

Description:

Redesigning Unsplash Using Styled Components

Writing future-proof CSS is hard. Conflicting classnames, specificity issues, and so on, come up when you have to write and maintain thousands of lines of CSS. To get rid of the aforementioned issues, Styled Components was created.

Styled Components makes it easy to write your CSS in JS and makes sure there are no conflicting classnames or specificity issues with multiple other benefits. This makes writing CSS a joy.

In this tutorial, we’ll explore what CSS in JS is, the pros and cons of styled-components, and finally, we’ll redesign Unsplash using Styled Components. After completing this tutorial, you should be able to quickly get up and running with Styled Components.

Note: Styled Components was specifically built with React in mind, so you have to be using React to use Styled Components.

Prerequisites

For this tutorial, you need a basic knowledge of React.

Throughout the course of this tutorial we’ll be using yarn. If you don’t have yarn already installed, then install it from here.

To make sure we’re on the same page, these are the versions used in this tutorial:

Node 12.6.0 npx 6.4.1 yarn 1.17.3 Evolution of CSS

Before CSS-in-JS was created, the most common way to style web apps was to write CSS in a separate file and link it from the HTML.

But this caused trouble in big teams. Everyone has their own way of writing CSS. This caused specificity issues and led to everyone using !important.

Then came Sass. Sass is an extension of CSS that allows us to use things like variables, nested rules, inline imports and more. It also helps to keep things organized and allows us to create stylesheets faster.

Even though Sass might be thought of as an improvement over CSS, it arguably causes more harm than good without certain systems put in place.

Later, BEM came in. BEM is a methodology that lets us reduce specificity issues by making us write unique classnames. BEM does solve the specificity problem, but it makes the HTML more verbose. Classnames can become unnecessarily long, and it's hard to come up with unique classnames when you have a huge web app.

After that, CSS Modules were born. CSS Modules solved what neither Sass nor BEM could — the problem of unique classnames — by tooling rather than relying on the name given by a developer, which in turn solved specificity issues. CSS Modules gained a huge popularity in the React ecosystem, paving the way for projects like glamor.

The only problem with all these new solutions was that developers were made to learn new syntaxes. What if we could write CSS exactly how we write it in a .css file but in JS? And thus styled-components came into existence.

Styled Components uses Template Literals, an ES6 feature. Template literals are string literals allowing embedded expressions. They allow for multi-line strings and string interpolation features with them.

The main selling point of Styled Components is that it allows us to write exact CSS in JS.

Styled Components has a lot of benefits. Some of the pros and cons of Styled Components are listed below.

Pros

There are lots of advantages to using Styled Components.

Injecting Critical CSS into the DOM

Styled Components only injects critical CSS on the page. This means users only download CSS needed for that particular page and nothing else. This loads the web page faster.

Smaller CSS bundle per page

As it only injects styles that are used in the components on the page, bundle size is considerably smaller. You only load the CSS you need, instead of excessive stylesheets, normalizers, responsiveness, etc.

Automatic Vendor Prefixing

Styled Components allows you to write your CSS and it automatically vendor prefixes according to the latest standard.

Remove unused CSS

With Styled Components, it's easier to remove unused CSS or dead code, as the styles are colocated with the component. This also impacts on reducing bundle size.

Theming is easy

Styled Components makes it really easy to theme a React applications. You can even have multiple themes in your applications and yet easily maintain them.

Reduces the number of HTTP requests

Since there are no CSS files for resets, normalizers, and responsiveness, the number of HTTP requests are considerably reduced.

Unique Classnames

Styled Components generates unique classnames every time a build step takes place. This allows avoiding naming collisions or specificity issues. No more having global conflicts and being forced to resolve them with !important tags.

Maintenance is easy

Styled Components allows you to colocate styles with the component. This allows for painless maintenance. You know exactly which style is affecting your component, unlike in a big CSS file.

Cons

Of course, nothing's perfect. Let's look at some downsides associated with Styled Components.

Unable to Cache Stylesheets

Generally, a web browser caches .css files when a user visits a website for the next visit, so it doesn't have to download the same .css file again. But with styled-components, the styles are loaded in the DOM using the <style> tag. Thus, they can’t be cached and every time user has to request styles when they visit your website.

React specific

Styled Components was made with React in mind. Thus, it’s React specific. If you use any other framework, then you can’t use Styled Components.

However, there’s an alternative very similar to styled-components known as emotion which is framework agnostic.

The post How to Redesign Unsplash Using Styled Components appeared first on SitePoint.

4 Key Principles to Remember When Building B2B Ecommerce Websites

Aug 26, 2019

Description:

4 Key Principles to Remember When Building B2B Ecommerce Websites

This article was created in partnership with StudioWorks. Thank you for supporting the partners who make SitePoint possible.

B2B ecommerce businesses are currently facing a bit of a boom. Forrester estimates that B2B ecommerce revenues will reach $1.8 trillion in the US in the next four years. And a recent BigCommerce study found that 41% of B2B retailers predict their online sales to increase more than 25% by the end of the year.

So if you’re building a B2B ecommerce storefront to capitalize on this boom, it’s important that you take the time to ensure that the website has all the right functionality to receive and fulfill orders, and to deliver a great shopping experience to your buyers.

In this post, we’ll take a look at some of the key principles you’ll need to keep in mind when tackling a B2B ecommerce website build.

But before we begin, let’s put everything into a bit of context.

Key Differences Between B2C and B2B Ecommerce Sites

B2B ecommerce companies, of course, provide the goods and services that other companies need to operate and grow. In the ecommerce space, when we refer to a B2B company, we’re generally talking about firms that sell physical goods on a wholesale basis, but other types of B2B companies have been known to get into the ecommerce game.

For example, industrial suppliers or consultancy service providers are generally B2B companies, and they may or may not offer online purchasing options too. B2C companies, on the other hand, sell their products and services direct to individual customers.

b2c companiesImage source

Currently, the B2B ecommerce opportunity is huge compared to B2C ecommerce, which has become harder to crack due to high levels of competition and low barriers to entry. B2B buyers are becoming increasingly interested in making purchases online. Sellers, meanwhile, are only starting to make it possible.

But just because the demand is there doesn’t mean corporate buyers are expecting the same type of experiences from B2B ecommerce that they get on Amazon. Here are a few key differences between B2B and B2C, when it comes to ecommerce interfaces and customer experiences.

Breadth of audience

One major difference between B2B and B2C is the scale of their target audience. B2B sites deal with buyers who have simple, targeted profiles such as CTOs at tech startups. On the flip side, B2C sites have a broader group of people to cater to — for instance, moms with toddlers or millennials who are into sneakers.

For this reason, B2B ecommerce sites typically have a different purchasing user flow which involves more personalization.

Average price point

Most B2C ecommerce sites sell to hundreds of thousands of customers because their products typically sell at a lower price point. On the other hand, B2B sites may have less than 100 customers.

B2B ecommerce sites often use quote builders and set up different technology to be able to accept and process larger orders. For example, this may include options for recurring payments, bulk discounts, and shipping.

The decision-making process

B2C buying decisions are made fairly quickly, as they’re generally less rational and more based on impulse. Lower pricing points make this possible. In B2B decisions, the purchasing manager may have to get approval from senior executives, finance, marketing, and legal departments before placing an order.

To streamline the decision-making process, B2B ecommerce site owners offer tailored pricing to buyers. They also set up customer accounts to make it easy for buyers to fill out orders and complete transactions.

With the above in mind, let’s take a closer look at some of the important principles to guide you as you build your next B2B ecommerce website.

1. Integrate with an ERP Solution

As a B2B company, you’ll be able to significantly increase productivity by integrating an ERP solution with your ecommerce site.

The key benefit is that your inventory levels will automatically update in two places. Inventory availability figures can appear on the front end of the site as goods are added to inventory, giving customers a better shopping experience. Plus, with access to ERP data on the back end, you can enable your staff to easily meet orders and forecast product demand.

Another key benefit of integrating an ERP solution is that you won’t need to hire additional workers in case product demand goes up.

Here are some of the most common ERP integration patterns:

Migration. Data migration ERP refers to the movement of a particular set of data between two systems at a specific point in time. The migration can either be on an as-needed basis through an API or on command by setting the configuration parameters to pass into the API calls. Broadcast. The broadcast ERP integration pattern involves the transfer of data from one source system to multiple destination systems in real time. Broadcast systems help move data quickly between systems and keep multiple systems up to date across time. Aggregation. This ERP pattern receives data from multiple systems and stores it into only one system. It eliminates the need to regularly run multiple migrations, which removes the risk associated with data synchronization and accuracy. Bi-directional synchronization. Bi-directional sync ERP integration is useful in situations where different systems are required to perform different functions in the same data set. Correlation. Correlation is similar to bi-directional ERP integration. The difference is that the former synchronizes objects only if they’re present in both systems. Process APIImage source

BigCommerce offers a number of ERP integrations, including Brightpearl, Stitch Labs, NetSuite ERP Connector by Patchworks, and Acumatica Cloud ERP by Kensium via the eBridge Connections systems integrator.

The post 4 Key Principles to Remember When Building B2B Ecommerce Websites appeared first on SitePoint.

25+ JavaScript Shorthand Coding Techniques

Aug 26, 2019

Description:

Child between piles of books

This really is a must read for any JavaScript developer. I have written this guide to shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what is going on, I have included the longhand versions to give some coding perspective.

August 26th, 2019: This article was updated to add new shorthand tips based on the latest specifications. If you want to learn more about ES6 and beyond, sign up for SitePoint Premium and check out our extensive library of modern JavaScript resources.

1. The Ternary Operator

This is a great code saver when you want to write an if..else statement in just one line.

Longhand:

const x = 20; let answer; if (x > 10) { answer = "greater than 10"; } else { answer = "less than 10"; }

Shorthand:

const answer = x > 10 ? "greater than 10" : "less than 10";

You can also nest your if statement like this:

const answer = x > 10 ? "greater than 10" : x < 5 ? "less than 5" : "between 5 and 10"; 2. Short-circuit Evaluation Shorthand

When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined, or empty. You can either write a long if statement with multiple conditionals, or use a short-circuit evaluation.

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }

Shorthand:

const variable2 = variable1 || 'new';

Don’t believe me? Test it yourself (paste the following code in es6console):

let variable1; let variable2 = variable1 || 'bar'; console.log(variable2 === 'bar'); // prints true variable1 = 'foo'; variable2 = variable1 || 'bar'; console.log(variable2); // prints foo

Do note that if you set variable1 to false or 0, the value bar will be assigned.

3. Declaring Variables Shorthand

It's good practice to declare your variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.

Longhand:

let x; let y; let z = 3;

Shorthand:

let x, y, z=3; 4. If Presence Shorthand

This might be trivial, but worth a mention. When doing “if checks”, assignment operators can sometimes be omitted.

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

Note: these two examples are not exactly equal, as the shorthand check will pass as long as likeJavaScript is a truthy value.

Here is another example. If a is NOT equal to true, then do something.

Longhand:

let a; if ( a !== true ) { // do something... }

Shorthand:

let a; if ( !a ) { // do something... } 5. JavaScript For Loop Shorthand

This little tip is really useful if you want plain JavaScript and don't want to rely on external libraries such as jQuery or lodash.

Longhand:

const fruits = ['mango', 'peach', 'banana']; for (let i = 0; i < fruits.length; i++)

Shorthand:

for (let fruit of fruits)

If you just wanted to access the index, do:

for (let index in fruits)

This also works if you want to access keys in a literal object:

const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'} for (let key in obj) console.log(key) // output: continent, country, city

Shorthand for Array.forEach:

function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } [2, 5, 9].forEach(logArrayElements); // a[0] = 2 // a[1] = 5 // a[2] = 9 6. Short-circuit Evaluation

Instead of writing six lines of code to assign a default value if the intended parameter is null or undefined, we can simply use a short-circuit logical operator and accomplish the same thing with just one line of code.

Longhand:

let dbHost; if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; }

Shorthand:

const dbHost = process.env.DB_HOST || 'localhost'; 7. Decimal Base Exponents

You may have seen this one around. It’s essentially a fancy way to write numbers without the trailing zeros. For example, 1e7 essentially means 1 followed by 7 zeros. It represents a decimal base (which JavaScript interprets as a float type) equal to 10,000,000.

Longhand:

for (let i = 0; i < 10000; i++) {}

Shorthand:

for (let i = 0; i < 1e7; i++) {} // All the below will evaluate to true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000; 8. Object Property Shorthand

Defining object literals in JavaScript makes life much easier. ES6 provides an even easier way of assigning properties to objects. If the variable name is the same as the object key, you can take advantage of the shorthand notation.

The post 25+ JavaScript Shorthand Coding Techniques appeared first on SitePoint.

SitePoint Premium New Releases: Form Design + Cloning Tinder

Aug 23, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Form Design Patterns

On first glance, forms are simple to learn. But when we consider the journeys we need to design, the users we need to design for, the browsers and devices being used; and ensuring that the result is simple and inclusive, form design becomes a far more interesting and bigger challenge.

➤ Read Form Design Patterns.

Cloning Tinder Using React Native Elements and Expo

In this tutorial, we’ll be cloning the most famous dating app, Tinder. We’ll then learn about a UI framework called React Native Elements, which makes styling React Native apps easy. Since this is just going to be a layout tutorial, we’ll be using Expo, as it makes setting things up easy.

➤ Read Cloning Tinder Using React Native Elements and Expo.

And More to Come…

We're releasing new content on SitePoint Premium regularly, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Form Design + Cloning Tinder appeared first on SitePoint.

How to Use Windows Subsystem for Linux 2 and Windows Terminal

Aug 22, 2019

Description:

Using Windows Subsystem for Linux 2 and Windows Terminal

In this article, you’ll learn how you can set up and run a local Linux shell interface in Windows without using a virtual machine. This not like using terminals such as Git Bash or cmder that have a subset of UNIX tools added to $PATH. This is actually like running a full Linux kernel on Windows that can execute native Linux applications. That's pretty awesome, isn't it?

If you’re an experienced developer, you already know that Linux is the best platform on which to build and run server-based solutions using open-source technologies. While it’s possible to run the same on Windows, the experience is not as great. The majority of cloud hosting companies offer Linux to clients to run their server solutions in a stable environment. To ensure software works flawlessly on the server machine just like on the local development machine, you need to run identical platforms. Otherwise, you may run into configuration issues.

When working with open-source technologies to build a project, you may encounter a dependency that runs great on Linux but isn’t fully supported on Windows. As a result, Windows will be required to perform one of the following tasks in order to contribute to the project:

Dual Boot Windows and Linux (switch to Linux to contribute code) Run a Linux virtual machine using a platform such as Vagrant, VirtualBox, VMWare etc. Run the project application inside a Docker container

All the above solutions require several minutes from launch to have a full Linux interface running. With the new Windows Subsystem for Linux version 2 (WSL2), it takes a second or less to access the full Linux shell. This means you can now work on Linux-based projects inside Windows with speed. Let's look into how we can set up one in a local machine.

Installing Ubuntu in Windows

First, you'll need to be running the latest version of Windows. In my case, it's build 1903. Once you've confirmed this, you'll need to activate the Windows Subsystem for Linux feature. Simply go to Control-Panel -> Programs -> Turn Windows feature on or off. Look for "Windows Subsystem for Linux" and mark the checkbox. Give Windows a minute or two to activate the feature. Once it's done, click the restart machine button that appears next.

Enabling the WSL feature

Next, go to the Windows Store and install Ubuntu. The first Ubuntu option will install the latest versions. Other Ubuntu options allow you to install an older supported version.

Microsoft Store Linux

Once the installation is complete, you'll need to launch it from the menu. Since this is the first time, you’ll need to wait for the Ubuntu image to be downloaded and installed on your machine. This is a one-time step. The next time you launch, you’ll access the Linux Shell right away.

Once the image installation is complete, you’ll be prompted to create a new root user account inside this shell:

Installing Ubuntu in the command line

After you’ve created your credentials, feel free to type any Linux command to confirm you’re truly accessing a native Linux shell:

Ubuntu usage commands

You’ll be pleased to note that git, python3, ssh, vim, nano, curl, wget and many other popular tools are available out of the box. In a later section, we'll use sudo apt-get command to install more frameworks. First, let's look at several ways we can access this new Linux shell terminal interface. It's probably a good idea to upgrade currently installed packages:

$ sudo apt-get update && sudo ap-get upgrade Accessing Linux Shell Interface

The are several interesting ways of accessing the Linux shell interface.

Go to Windows Menu Start > type "Ubuntu". You can pin it to Start for quicker access

Open Command Prompt or Windows PowerShell and execute the command bash

In Windows explorer, SHIFT + right-mouse click a folder to open a special context menu. Click Open Linux shell here.

In Windows explorer, navigate to any folder you desire, then in the address bar type wsl, then press enter.

In Visual Studio Code, change the default terminal to wsl.

VS Code WSL Terminal

If you come across new ways, please let me know. Let's set up Node.js in the following section.

The post How to Use Windows Subsystem for Linux 2 and Windows Terminal appeared first on SitePoint.

These Are the Best Developer Tools & Services

Aug 22, 2019

Description:

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

As you've learned through experience, there's much involved in trying to find the right developers' tools or services for the task at hand.

It's a challenge. More and more software products and services are appearing on the market. But, every year it doesn't get any easier. This can be especially true in some cases. One case is where app developers have been trying to bridge the gap between software development and operations.

As you will see, open-source solutions go a long way toward resolving some of these problems. There are services that developers can use and that way can save them both time and money.

That's the case with the 6 products and services described below.

The post These Are the Best Developer Tools & Services appeared first on SitePoint.

Getting Started with React Native

Aug 21, 2019

Description:

With the ever-increasing popularity of smartphones, developers are looking into solutions for building mobile applications. For developers with a web background, frameworks such as Cordova and Ionic, React Native, NativeScript, and Flutter allow us to create mobile apps with languages we’re already familiar with: HTML, XML, CSS, and JavaScript.

In this guide, we’ll take a closer look at React Native. You’ll learn the absolute basics of getting started with it. Specifically, we’ll cover the following:

what is React Native what is Expo how to set up an React Native development environment how to create an app with React Native Prerequisites

This tutorial assumes that you’re coming from a web development background. The minimum requirement for you to be able to confidently follow this tutorial is to know HTML, CSS, and JavaScript. You should also know how to install software on your operating system and work with the command line. We’ll also be using some ES6 syntax, so it would help if you know basic ES6 syntax as well. Knowledge of React is helpful but not required.

What is React Native?

React Native is a framework for building apps that work on both Android and iOS. It allows you to create real native apps using JavaScript and React. This differs from frameworks like Cordova, where you use HTML to build the UI and it will just be displayed within the device’s integrated mobile browser (WebView). React Native has built in components which are compiled to native UI components, while your JavaScript code is executed through a virtual machine. This makes React Native more performant than Cordova.

Another advantage of React Native is its ability to access native device features. There are many plugins which you can use to access native device features, such as the camera and various device sensors. If you’re in need of a platform-specific feature that hasn’t been implemented yet, you can also build your own native modules — although that will require you to have considerable knowledge of the native platform you want to support (Java or Kotlin for Android, and Objective C or Swift for iOS).

If you’re coming here and you’re new to React, you might be wondering what it is. React is a JavaScript library for the Web for building user interfaces. If you’re familiar with MVC, it’s basically the View in MVC. React’s main purpose is to allow developers to build reusable UI components. Examples of these components include buttons, sliders, and cards. React Native took the idea of building reusable UI components and brought it into mobile app development.

What is Expo?

Before coming here, you might have heard of Expo. It’s even recommended in the official React Native docs, so you might be wondering what it is.

In simple terms, Expo allows you to build React Native apps without the initial headache that comes with setting up your development environment. It only requires you to have Node installed on your machine, and the Expo client app on your device or emulator.

But that’s just how Expo is initially sold. In reality, it’s much more than that. Expo is actually a platform that gives you access to tools, libraries and services for building Android and iOS apps faster with React Native. Expo comes with an SDK which includes most of the APIs you can ask for in a mobile app development platform:

Camera ImagePicker Facebook GoogleSignIn Location MapView Permissions Push Notifications Video

Those are just few of the APIs you get access to out of the box if you start building React Native apps with Expo. Of course, these APIs are available to you as well via native modules if you develop your app using the standard React Native setup.

Plain React Native or Expo?

The real question is which one to pick up — React Native or Expo? There’s really no right or wrong answer. It all depends on the context and what your needs are at the moment. But I guess it’s safe to assume that you’re reading this tutorial because you want to quickly get started with React Native. So I’ll go ahead and recommend that you start out with Expo. It’s fast, simple, and easy to set up. You can dive right into tinkering with React Native code and get a feel of what it has to offer in just a couple of hours.

That said, I’ve still included the detailed setup instructions for standard React Native for those who want to do it the standard way. As you begin to grasp the different concepts, and as the need for different native features arises, you’ll actually find that Expo is kind of limiting. Yes, it has a lot of native features available, but not all the native modules that are available to standard React Native projects are supported.

Note: projects like unimodules are beginning to close the gap between standard React Native projects and Expo projects, as it allows developers to create native modules that works for both React Native and ExpoKit.

Setting Up the React Native Development Environment

In this section, we’ll set up the React Native development environment for all three major platforms: Windows, Linux, and macOS. We’ll also cover how to set up the Android and iOS simulators. Lastly, we’ll cover how to set up Expo. If you just want to quickly get started, I recommend that you scroll down to the “Setting up Expo” section.

Here are the general steps for setting up the environment. Be sure to match these general steps to the steps for each platform:

install JDK install Android Studio or Xcode install Watchman update the environment variable install the emulator install Node install React Native CLI

You can skip to the section relevant to your operating system. Some steps — like setting up Android Studio — are basically the same for each operating system, so I’ve put them in their own section:

setting up on Windows setting up on Linux setting up on macOS setting up Android Studio install Node setting up Expo setting up emulators install React Native CLI troubleshooting common errors Setting Up on Windows

This section will show you how to install and configure the software needed to create React Native apps on Windows. Windows 10 was used in testing for this.

Install Chocolatey

Windows doesn’t really come with its own package manager that we can use to install the needed tools. So the first thing we’ll do is install one called Chocolatey. You can install it by executing the following command on the command line or Windows Powershell:

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

We can now install the other tools we need by simply using Chocolatey.

Install Python

Python comes with the command line tools required by React Native:

choco install -y python 2 Install JDK

The JDK allows your computer to understand and run Java code. Be sure to install JDK version 8 as that’s the one required by React Native:

choco install jdk8 Install NVM

Node has an installer for Windows. It’s better to use NVM for Windows, as that will enable you to install multiple versions of Node so that you can test new versions, or use a different version depending on the project you’re currently working on. For that, you can use NVM for Windows. Download nvm-setup.zip, extract it and execute nvm-setup.exe to install it.

Install Watchman

Watchman optimizes the compilation time of your React Native app. It’s an optional install if you’re not working on a large project. You can find the install instructions on their website.

Update the Environment Variables

This is the final step in setting up React Native on Windows. This is where we update the environment variables so the operating system is aware of all the tools required by React Native. Follow these steps right before you install the React Native CLI.

Go to Control Panel → System and Security → System. Once there, click the Advanced system settings menu on the left.

Windows advanced system settings

That will open the system properties window. Click on the Environment Variables button:

System properties

Under the User variables section, highlight the Path variable and click the edit button.

On the edit screen, click the New button and enter the path to the Android SDK and platform tools. For me, it’s on C:\users\myUsername\AppData\Local\Android\Sdk and C:\users\myUsername\AppData\Local\Android\Sdk\platform-tools. Note that this is also where you add the path to the JDK if it isn’t already added:

add path

The post Getting Started with React Native appeared first on SitePoint.

How the Top 1% of Candidates Ace Their Job Interviews

Aug 19, 2019

Description:

You've done it.
 
You've made it through the initial screening process. You've just earned an interview with one of the most prestigious and successful companies in your industry. As you're waiting in the office with three other candidates, a fourth candidate walks in.
 
He has an interview scheduled, the same as you.
 
There's something odd about this interviewee. He already knows everyone there. He's on a first-name basis with the receptionist. Everyone likes him and thinks highly of him. Instead of waiting in the lobby with the rest of you, he's immediately ushered into one of the offices.
 
Who is this guy?
 

This is an everyday reality for elite job candidates

 
How is this possible?
 
Candidates like these are pretty uncommon. Not because they're so special, but because of their decision-making process. What makes their decision-making process different?
 

They win coveted jobs and promotions in the face of intense competition They ask for and receive substantially higher salaries than their coworkers Employers create positions specifically for them (to keep them) They earn positions before they're publicly available These job candidates seem to receive preferential treatment wherever they go
 
Something is going on, but what?
 
These elite candidates have a very different set of attitudes, behaviors, and habits than most other employees. Is it simply because they're better than everyone else?
 
Not at all.

The post How the Top 1% of Candidates Ace Their Job Interviews appeared first on SitePoint.

9 Key Ways to Turbocharge Your Design Career

Aug 19, 2019

Description:

9 Key Ways to Turbocharge Your Design Career

This article was created in partnership with StudioWorks. Thank you for supporting the partners who make SitePoint possible.

Sure, you need a certain minimal viable level of design skill prowess if you want to have a successful career as a designer. But a lot more than that goes into it, too. Think about how many people you know who can cook amazing food but who would never last five minutes in a restaurant kitchen during the lunch rush.

It would be great if we could just sit down, design pretty things, and go home. Or better yet, just chill in our home studios, creating. Unfortunately or not, design is a business just like everything else, and that means you’re going to have to put time, effort, and sometimes money into cultivating the soft skills and business side of your design career.

This means managing your time well, marketing yourself, building a brand, experimenting, maybe launching a side business, and generally just putting your name and work out there for people to find.

These days, it’s not enough to have a portfolio. That’s just table stakes. You need to plan out your whole career — with the understanding that plans change.

Let’s look at some of the things you need to do to develop your career until you’re basically the next Jen Simmons or Jeffrey Zeldman.

Get Your Communication Skills Flowing

Communication skills come naturally to some, and not so naturally to others. In both cases, those skills are rather drastically affected by the people you have to communicate with most. Most of us find ways to convey our thoughts and intentions clearly to our friends, and also to people in our industry and hobby communities. We learn the lingo, we learn which topics encourage discussion, and which are best avoided.

Writing for anyone who’s not a part of your immediate community, and especially writing for people who don’t know what you know, is hard. Speaking to them in person can be harder, depending on how you, as a person, prefer to communicate. But, all the same, you have to.

Even if you work in an agency amongst other designers right now, there will inevitably come a time when you have to pitch clients on the benefits of your work, explain to a newbie the processes you use, or defend your decisions to developers who push back, or to other people who just don’t know what you know.

If there’s any single thing you take away from this article, focus on your communication skills. It will affect your career more than anything else on this list. If you’re looking for a place to start learning those skills, CopyBlogger always has you covered — at least for the writing side of it.

Branch Out into Side Businesses

Some side projects are great, strictly because they allow us to get out of our comfort zones, try new things and regain a sense of creative discovery.

Others may overlap with the activities you’d use to build a personal brand, which we’ll get into shortly, with the added benefit that they can bring in extra money while you’re establishing yourself as an expert in the field.

Here are some of the more popular ways of doing this.

1. Courses

Sure, you can throw some tutorials onto your blog, or onto YouTube, for free. And you probably should. But if you want to make a side business out of teaching others what you do, and further your career in the process, you’re going to need an actual product. This is where courses come in.

Quality video courses, which are quite popular these days, can be expensive and time-consuming to set up. It’s gotten easier, though, now that you can use all-in-one course development and delivery services like Kajabi. This platform can help you manage everything relating to your premium educational content and running the business around it.

You can create membership sites, host live events, create automation funnels, upsells, maintain a blog and manage contacts all in one place, so it’s not as hard as it used to be. However, you still have to get a half-decent camera, a half-decent microphone, and ideally learn some basic video editing skills.

This is a side hustle I’d frankly only recommend if you’ve got some time on your hands, and a bit of extra money for some beginner hardware. It can be quite rewarding, though, so don’t dismiss the idea out of hand.

2. Live Streaming

I mentioned live events in the last section, so I thought I’d mention streaming as its own thing. Streaming doesn’t have to be educational, although education is probably the best way to sell your expertise. You could just sit there and share designer memes on Twitch if you want.

The problem is mostly that the requirements for video and audio haven’t changed, and depending on how you set up your stream schedule, it can be even more demanding than making video courses.

Then again, if you don’t mind not making a lot of money, and want to do it for fun, it’s still a great way to “meet” new people, and to be seen.

3. Paid Newsletters

Now this is an option I’d save for when you’ve already built a bit of an audience by other means, such as social media and/or blogging. But Substack has made it easier than ever for people to pay writers directly.

If you’ve got wisdom to share, and if you think people would be willing to pay to have that wisdom beamed straight into their inboxes, go on and have at it.

4. Make Stuff for Other Designers

Plenty of designers and agencies have kept up a healthy “passive” revenue stream by making resources for other designers.

Be it a template, a WordPress theme, a Sketch UI kit, an icon font, or whatever else, if it’s valuable to you because it solves problems that you have, then there’s a good chance your peers will be willing to pay for it. Just don’t forget to also give stuff away once in a while. Gratitude goes a long way in the design world.

The post 9 Key Ways to Turbocharge Your Design Career appeared first on SitePoint.

SitePoint Premium New Releases: Going Offline + React Native

Aug 16, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Going Offline

Jeremy Keith introduces you to service workers (and the code behind them) to show you the latest strategies in offline pages. Learn the ins and outs of fetching and caching, enhance your website’s performance, and create an ideal offline experience for every user, no matter their connection.

➤ Read Going Offline.

Integrating AdMob in React Native and Expo

Google AdMob is one way to install ads into any mobile application in order to monetize it. Installing and configuring AdMob in bare React Native can be a cumbersome process. But it’s relatively simple to install when using a toolchain like Expo — we'll show you how.

➤ Read Integrating AdMob in React Native and Expo.

And More to Come…

We're releasing new content on SitePoint Premium regularly, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Going Offline + React Native appeared first on SitePoint.

How to Build a Cipher Machine with JavaScript

Aug 15, 2019

Description:

I was overjoyed recently when I read the news that the British mathematician, Alan Turing will feature on the Bank of England's new £50 note. Turing occupies a special place in the hearts of computer nerds for effectively writing the blueprints for the computer. He also helped to break the notoriously difficult naval Enigma code used by the Nazi U-boats in World War II. In honor of this I decided a quick tutorial to build a cipher machine using the JavaScript skills that are covered in my book JavaScript Novice To Ninja.

The cipher we'll be using is the Caesar cipher, named after the Roman emperor, Julius Caesar. It is one of the most simple ciphers there are and simply shifts each letter along a set number of places. For example, the phrase 'Hello World' would become 'KHOOR ZRUOG' using a shift of 3 (which it is the shift that Julius Caesar is thought to have used).

Our cipher machine

You can see an example of the finished code here. Have a play around at writing some secret messages to get a feel for how it works.

To get started, fire up your favorite text editor and save the following as caesar.html:

The post How to Build a Cipher Machine with JavaScript appeared first on SitePoint.

10 Tools to Help You Manage Your Agile Workflows

Aug 15, 2019

Description:

Workflows

This article was created in partnership with monday.com. Thank you for supporting the partners who make SitePoint possible.

Software development remains a complex task which balances analysis, planning, budget constraints, coding, testing, deployment, issue fixing, and evaluation. Large projects often fail because no one can comprehend the full extent of requirements from the start. Those requirements then change with each revision of the product.

An agile development approach can mitigate the risks. There are many flavors of 'agile', but most rapidly evolve a product over time. Self-organising teams of stakeholders, designers, developers, and testers collaborate to produce a minimum viable product which is extended and revised during a series of iterations - or sprints.

Ideally, a fully-working product is available at the end of every sprint. Changing requirements can determine the priorities for the next sprint.

Crucial Collaboration

Communication distinguishes agile from more traditional waterfall workflows. Teams work together on a particular feature so developers and designers can quickly provide feedback when a requirement becomes impractical or more cost-effective options can be identified.

A variety of tools and software is available to help teams collaborate. There are two general options:

Separate tools for specific tasks. For example, a feature may be described in a document which is transferred to a to-do list which becomes a pull request and inevitably has bugs reported. All-in-one tools which manage the whole process.

The following tools can all help manage your agile workflow.

monday.com

monday.com has rapidly become the full agile management solution for 80,000 organizations within a few years.

monday.com dashboard

monday.com offers a completely customizable application for numerous use-cases such as agile project management. Powerful features include:

quick-start project templates (there are over 100 template that are completely customisable to fit your needs) attractive at-a-glance project state dashboards, so you can easily track progress and identify bottlenecks in a "big picture" view intuitive collaboration with team members and clients using @mentions easy file sharing, so you'll always know where your most updated files are multiple views to track progress (reports, Kanban boards, Gantt charts, calendars, timelines etc.) task management, time and deadline tracking automations and integration with other applications to keep everything in one place, so you can focus on the important stuff.

Prices start from $25 per month for five users, but a 30 day free trial is available so you can assess the system.

The post 10 Tools to Help You Manage Your Agile Workflows appeared first on SitePoint.

What Every Dev Company Needs to Know about NoOps Development

Aug 13, 2019

Description:

It seems like everything is getting automated these days.

And I mean everything.

Who would’ve thought that we’d be automating development teams, though?

69% of development companies agree that process and automation improvement is a top priority, so it makes sense we’re heading in this direction.

This rise of automation has formed a new development model known as NoOps, which stands for no operations.

The name means that this approach involves no operations input, cutting out the "operate" step of the continuous development model.

Continuous development model

That’s right. The developers are capable of launching, testing, and fixing apps on the fly without any interruptions or downtime.

Follow along as I further cover what NoOps is, the benefits of using it, and how to implement it.

What is NoOps?

NoOps is a new development approach that involves relieving developers of needing to constantly work with operations members, speeding up deployment time, testing, and workflow.

It stems from the previously popular model of developers and operations teams working closely called DevOps.

Instead of working together, service providers give development teams the proper cloud infrastructure, patching, backups, and resources to work on their own.

Traditional DevOps vs NoOps

That means programmers no longer require feedback and approval during development, and can operate completely independently.

This also allows the operations department of a company to focus on what they do best: project management, talent acquisition, and so on.

However, NoOps is typically most beneficial for startups that begin with this continuous development model. It is much more difficult to switch to NoOps when you have existing environments, pipelines, and deployment procedures.

As an example, NoOps does not work well for enterprises that are still stuck with a monolithic legacy application. This would require a re-write of most of their codebase to make it fit with the NoOps ideology.

Additionally, if a company adopts NoOps later in the business cycle, they may have to shrink the size of their operations team.

If a startup launches with a NoOps model from the beginning, they have the potential of staying lean for longer. The saved resources can be put towards other aspects of business growth, like marketing.

What Are the Benefits of NoOps?

There are many benefits to be gained by adopting a NoOps model. The first of which is that it maximizes development time.

The post What Every Dev Company Needs to Know about NoOps Development appeared first on SitePoint.

A Guide to Visual Testing with Percy

Aug 13, 2019

Description:

A Guide to Visual Testing with Percy

This article was created in partnership with Percy. Thank you for supporting the partners who make SitePoint possible.

Visual testing is the automated process of ensuring your user interface looks correct in different browsers and at different screen widths.

Most development teams rely solely on unit and integration tests. While this practice helps ensure application logic is working correctly, it fails to detect visual defects at the UI level. Implementing this type of test allows visual problems to be detected early and to get fixed before the product is released.

In this tutorial, you’ll learn how to set up and run visual testing for your project using Percy. For demonstration purposes, we’ll be using a single-page application that’s API-driven using real-world data. You’ll learn how to visually test UIs that output dynamic data, and about Percy’s visual review and approval workflow.

Prerequisites

Visual testing is a topic for intermediate and advanced users. To follow this tutorial, you’ll need to be comfortable writing code in JavaScript ES6+ syntax. We won’t be doing actual app development, but you should at least have some experience using the following libraries in case you want to tweak something in the demo project we’ll be using:

Express.js + RESTful APIs jQuery Axios CSS frameworks

You should also be familiar with Git branching and different types of branching strategies. Familiarity with any testing framework will also help you easily understand the concepts discussed in this article. You’ll need to have a GitHub account before you can proceed with this tutorial. We’ll use this demo project as our starting point.

About Percy

Percy provides developers with a platform and workflow to run visual testing and reviews on web apps, static sites, or component libraries. There’s a free plan that supports unlimited team members, 5,000 snapshots per month (with a one-month history), and unlimited projects.

To get started with Percy, install one of its SDKs into the project you want to visually test. It’s the same as installing a testing framework like Mocha or Jest. Next, you write a script and run it just as you would with any type of test.

However, in Percy’s case, DOM snapshots of your web application are captured and uploaded for rendering on Percy’s infrastructure. Percy then detects and highlights visual differences between new and previous snapshots, also known as the baselines. The results are displayed in Percy, where you can review and determine whether the UI looks correct or needs to be fixed.

Percy renders each snapshot in Chrome and Firefox and can render at up to ten different screen resolutions. That’s quite impressive, as doing this manually is tiresome. I encourage you to read through the following docs to gain a deeper understanding:

The post A Guide to Visual Testing with Percy appeared first on SitePoint.

How to Use Bannersnack to Generate Amazing Banners in Seconds

Aug 12, 2019

Description:

How to Use Bannersnack to Generate Amazing Banners in Seconds

This article was created in partnership with StudioWorks. Thank you for supporting the partners who make SitePoint possible.

Banner ads have been around since the dawn of the Internet. And badly designed banner ads that annoy many users have been around just a long. But 30 years later businesses still pay to put them on websites and in their ad rotation, so they must work when done right. Right?

Banner ads, especially animated ones, are being used more than ever on social media profiles and as social ads too, as marketers realize the power of video in catching attention. Today’s banner ads are sophisticated and well designed, and can be highly effective. But for designers, they present a huge challenge.

Coding Banner Ads Is Hard and Expensive

Banner ads, especially animated ones, are notoriously hard to code in HTML5. Sure, you can create animated banners in Flash, but Apple’s iOS doesn’t support them, and Adobe says they’re shutting down Flash altogether in 2020.

GIFs are another possible solution, but they usually have poor resolution and most web users associate GIFs with memes and humor, rather than serious products. So you’re left with HTML5.

Coding HTML5 ads — in particular, animated ones — requires expertise, and expertise is expensive. Good coders know their value, and finding one you can trust can be an impossible task. Freelance platforms might seem the obvious place to start, but coders worth their salt soon move away from third-party sites.

Fortunately, this is the age of SaaS, and designers can now use applications like Bannersnack with drag-and-drop interfaces that lets you design banner ads quickly and efficiently.

What Does Bannersnack Do?

Bannersnack is an online app that helps you design fully responsive banner ads for websites and social media platforms — without having any coding or design skills. The Bannersnack creators figured out all the hard coding stuff, so you just log in, choose your size, add your image, select colors and fonts, and get creative.

Bannersnack home pageImage source: Bannersnack

Let’s take a quick run through the Bannersnack platform and see what it can do.

1. Pick your size

Start with a custom size and orientation (vertical, horizontal, and square), or choose a pre-set size. You can even pick a Facebook ad or an Instagram post:

Picking a sizeImage source: Bannersnack 2. Design your ad

You can either design from scratch, or use an existing Bannersnack template. Bannersnack offers static or animated designs in its template gallery, so you can get started even without having a design idea.

Designing the adImage source: Bannersnack 3. Add images and text

Customize your design with just a few clicks. If you can use Mailchimp or other SaaS marketing tools, you can use Bannersnack. Edit headlines, text, buttons, background, add your own logos and images, and change design nuances like line heights and transparencies. You can create beautifully designed banner ads that are a perfect match for your existing brand standards and colors.

Adding images and textImage source: Bannersnack 4. Animate with ease

It’s no secret that animated ads are more engaging and drive action better than static ads. Readers are more likely to react to videos than non-animated content, and more likely to visit the publisher’s page or website.

Videos drive action

Videos drive actionImage source: Impactbnd.com

But animation is notoriously tricky. Bannersnack has managed to solve that hurdle — with HTML5 animations that include fade-in, slide-in, and bounces. These aren’t full video ads, but they’ll still pull a user’s eyes towards them on a busy web page and boost your engagement. They have the added advantage of loading quickly — which is vital for preventing mobile users from scrolling past your ad before it’s even loaded.

Bannersnack’s HTML5 editor has an intuitive and user-friendly interface and slide management system to make animation simple. Try one of the 32 pre-made animation presets to animate any part of your ad:

Pre-made animation presetsScreenshot source

Or, create custom animations and adjust things like duration, delay, and transitions.

Creating custom animations

The post How to Use Bannersnack to Generate Amazing Banners in Seconds appeared first on SitePoint.

SitePoint Premium New Releases: Responsive CSS + React Native

Aug 9, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

14 Essential Responsive CSS Techniques

Over 6 easy chapters, we’ll help you to get a grounding in responsive CSS techniques, helping you make your sites and apps look great on any device.

Starting with an examination of the em responsive unit and highlight its shortcomings, then move on to the rem unit and how it can overcome them.

Finally, we’ll look at how media queries can work with em and rem to provide a complete responsive web design solution.

➤ Read 14 Essential Responsive CSS Techniques.

Using Android Native Modules in React Native

In this tutorial, we’ll develop a simple application that shows the current battery percentage and charging status. For this, we’ll create a native module with methods to fetch the required information.

➤ Read Using Android Native Modules in React Native.

And More to Come…

We're releasing new content on SitePoint Premium regularly, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Responsive CSS + React Native appeared first on SitePoint.

How to Create Web Animations with Anime.js

Aug 8, 2019

Description:

There are many JavaScript animation libraries out there, but Anime.js is one of the best. It's easy to use, has a small and simple API, and offers everything you could want from a modern animation engine. The library has a small file size and supports all modern browsers, including IE/Edge 11+.

The only thing that could stop you from using Anime.js right away is its minimal, zen-like documentation. I like the compact, structured, elegant approach it takes, but I think that a more detailed explanation would be helpful. I'll try to fix this issue in this tutorial.

Getting Started With Anime.js

To get started, download and include the anime.js file in your HTML page:

<script src="path/to/anime.min.js"></script>

Alternatively, you can use the latest version of the library hosted on a CDN:

<script src="https://cdn.jsdelivr.net/npm/animejs@3.0.1/lib/anime.min.js"></script>

Now, to create an animation, we use the anime() function, which takes an object as an argument. In that object, we describe all the animation details.

let myAnimation = anime({ /* describe the animation details */ });

There are several kinds of properties used to describe the animation. They are grouped into four distinct categories:

Targets - this includes a reference to the element(s) we want to animate. It could be a CSS selector (div, #square, .rectangle), DOM node or node list, or plain JavaScript object. There is also an option to use a mix of the above in an array. Properties - this includes all properties and attributes that can be animated when dealing with CSS, JavaScript objects, DOM, and SVG. Property Parameters - this includes property-related parameters like duration, delay, easing, etc. Animation Parameters - this includes animation-related parameters like direction, loop, etc.

Let's now see how this applies in practice. Consider the following example:

let animation = anime({ targets: 'div', // Properties translateX: 100, borderRadius: 50, // Property Parameters duration: 2000, easing: 'linear', // Animation Parameters direction: 'alternate' });

See the Pen
AnimeJS: Basic Example
by SitePoint (@SitePoint)
on CodePen.

Note: I'm not going to cover the HTML and CSS sections of the code in the tutorial. These tend to be easy to grasp without additional explanation. You can find and explore the HTML and CSS in the embedded pens that follow each example.

In the above example:

We select the green square (the styled div). We move it 100 pixels to the left while transforming it into a circle. We set all this to happen smoothly in two seconds (linear means that no easing will be applied to the animation). By setting the direction property to alternate, we instruct the div element to go back to its initial position and shape after animation completion. Anime.js does that by playing the animation in reverse order.

You may notice that I don't use any units when specifying property values. That's because if the original value has a unit, it is automatically added to the animated value. So, we can safely omit the units. But if we want to use a specific unit we must add it intentionally.

Let's create something more meaningful.

Creating a Pendulum Animation

In this example, we will create a pendulum animation. After we "draw" a pendulum using our HTML and CSS skills, it's time to bring it to life:

let animation = anime({ targets: '#rod', rotate: [60, -60], // from 60 to -60 degrees duration: 3000, easing: 'easeInOutSine', direction: 'alternate', loop: true });

See the Pen
AnimeJS: Pendulum Animation
by SitePoint (@SitePoint)
on CodePen.

In this animation, we use the so-called from-to value type, which defines a range of movement for the animation. In our case, the rod of the pendulum is rotated from 60 to -60 degrees. We also use easeInOutSine easing to simulate the natural motion of pendulum which slows down at peaks and gets faster at the bottom. We use the alternate option again to move the pendulum in both directions and set the loop parameter to true to repeat the movement endlessly.

Well done. Let's move to the next example.

Creating a Battery Charge Animation

In this example, we want to create an animated icon of a charging battery, similar to the icons on our smartphones. This is easily doable with a bit of HTML and CSS. Here is the code for the animation:

The post How to Create Web Animations with Anime.js appeared first on SitePoint.

How to Set Up a Vue Development Environment

Aug 6, 2019

Description:

Setting Up a Vue Development Environment

If you’re going to do any serious amount of work with Vue, it’ll pay dividends in the long run to invest some time in setting up your coding environment. A powerful editor and a few well-chosen tools will make you more productive and ultimately a happier developer.

In this post, I’m going to demonstrate how to configure VS Code to work with Vue. I’m going to show how to use ESLint and Prettier to lint and format your code and how to use Vue’s browser tools to take a peek at what’s going on under the hood in a Vue app. When you’ve finished reading, you’ll have a working development environment set up and will be ready to start coding Vue apps like a boss.

Let’s get to it!

Want to learn Vue.js from the ground up? This article is an extract from our Premium library. Get an entire collection of Vue books covering fundamentals, projects, tips and tools & more with SitePoint Premium. Join now for just $9/month.

Installing and Setting Up Your Editor

I said that I was going to be using VS Code for this tutorial, but I’m afraid I lied. I’m actually going to be using VSCodium, which is an open-source fork of VS Code without the Microsoft branding, telemetry and licensing. The project is under active development and I’d encourage you to check it out.

It doesn’t matter which editor you use to follow along; both are available for Linux, Mac and Windows. You can download the latest release of VSCodium here, or download the latest release of VSCode here and install it in the correct way for your operating system.

Throughout the rest of this guide, for the sake of consistency, I’ll refer to the editor as VS Code.

Add the Vetur Extension

When you fire up the editor, you’ll notice a set of five icons in a toolbar on the left-hand side of the window. If you click the bottom of these icons (the square one), a search bar will open up that enables you to search the VS Code Marketplace. Type “vue” into the search bar and you should see dozens of extensions listed, each claiming to do something slightly different.

The post How to Set Up a Vue Development Environment appeared first on SitePoint.

5 Super CSS Grid Generators for Your Layouts

Aug 5, 2019

Description:

CSS Grid has turned out to be the most exciting evolution of CSS for quite a while. It's a specific CSS tool for building any web layout you can think of, from the simplest to the most complex. Today, CSS Grid is widely supported by all major browsers — it's clear that the dark days of hacking layouts using floats are gone forever.

Coding your CSS Grid layout directly in your code editor can be fun. Although the spec is a complex document, the key concepts you would need to build a simple layout don't have a steep learning curve. There are many resources that will get you started in no time, with CSS Master by Tiffany Brown, Rachel Andrew's Grid by Example, and Jen Simmons's Layout Land at the top of the list.

For those of you who feel more comfortable coding layouts using a visual editor, there are several interesting online options that you can try out.

Here are five CSS online tools with great visual interfaces that I'm going to put through their paces. The idea is: design your CSS Grid-based layouts in a few clicks, grab the code and run with it! Let's put this idea to the test and see what happens.

The Test Page Layout

In this article, I'm going to provide this simple hand-coded CSS Grid layout.

See the Pen
responsive CSS Grid example
by Maria Antonietta Perna (@antonietta)
on CodePen.

The layout has more than one HTML container tag working as a Grid container in a nested structure. I could have used the new subgrid feature that's been recently added to Grid, but at the time of writing only Firefox 69+ supports it, and none of the online generators discussed here have implemented this functionality yet.

For most of the CSS Grid generators, I'm going to focus my tests only on the <ul> that works as Grid container for the individual cards. This is what the code looks like:

.kitties > ul { /* grid styles */ display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); grid-gap: 1rem; }

Notice how the value of the grid-template-columns property alone enables you to add responsiveness without media queries by:

using the CSS Grid repeat() function together with the auto-fit property. You can add as many columns as you want and they will fit perfectly into the grid's width, whatever that may be. using the minmax() function, which ensures that each column is at least 320px wide, thereby displaying nicely on smaller screens.

Most CSS Grid generators don't include the ability to set the grid-template-columns using the CSS Grid features above, so you'll need to adjust the values generated by the tool inside media queries to add responsiveness to your layouts.

As I try out the CSS Grid generator tools, I'm going to replace the code above with the code generated by each tool, and examine its capabilities against the results displayed on the screen. The exception will be the fourth CSS Grid generator in the list, a Vue-powered tool by Masaya Kazama. This is because it makes it quite straightforward and quick to build the entire layout, including header and footer, with a few clicks and minor adjustments to one of its preset layouts.

Enough talking, let's dive right in!

1. CSS Grid Generator by Sarah Drasner

Sarah Drasner's CSS Grid generator

CSS Grid Generator is a shiny new generator coded by Sarah Drasner. The interface is super sleek and you can put together a basic CSS Grid layout in no time.

I generated a 2-column grid and dumped the code in my original example. You need media queries to make the layout responsive. Here's the result:

See the Pen
CSS Grid Generator #1 by Sarah Drasner
by Maria Antonietta Perna (@antonietta)
on CodePen.

The code looks like this:

.kitties > ul { /* grid styles */ display: grid; grid-template-columns: 320px 320px; grid-template-rows: 1fr 1fr; /* units for row and column gaps only available in px */ grid-column-gap: 16px; grid-row-gap: 16px; }

This tool lets you:

set the numbers and units of rows and columns drag within the boxes to place divs within them

At the time of writing, Sarah's CSS Grid generator lets you create simple implementations of CSS Grid-based layouts. This is clearly stated by the author:

Though this project can get a basic layout started for you, this project is not a comprehensive tour of CSS Grid capabilities. It is a way for you to use CSS Grid features quickly.

However, since this is a brand new open-source tool, it's still in active development and the community is invited to contribute. Complex features like minmax() are not implemented yet, but they might find their way into it at a later time.

2. LayoutIt by Leniolabs

LayoutIt is quite intuitive and has a few more features than CSS Grid Generator. For example, it lets you set the grid-gap property in px, em and % units, and set grid-template-columns and grid-template-rows using minmax(). However, this is not enough to ensure responsiveness, so you'll still need to adjust your values using media queries.

Also, I found no way of setting the grid-gap property, so you'll have to do it manually if you'd like some white space in between rows and columns.

Here's the result as I entered the generated code into my original example:

See the Pen
CSS Grid Generator #2 by Leniolabs
by Maria Antonietta Perna (@antonietta)
on CodePen.

Below is what the relevant code looks like:

.kitties > ul { /* grid styles */ display: grid; grid-template-columns: minmax(320px, 1fr) minmax(320px, 1fr); grid-template-rows: 1fr 1fr; /* grid gap not in code repeat, auto-fit, and auto-fill not there */ } 3. Griddy by Drew Minns

Griddy CSS Grid generator by Drew Minns

With Griddy you can set the number of columns and rows using fr, px, % and auto units, but there's no minmax() function. You can add gaps to your columns and rows using both px and % and set justify-items and align-items properties to align items within the grid. You'll need media queries for responsiveness.

Below is what the generated code displays on the screen:

See the Pen
CSS Grid Generator #3 by Drew Minns
by Maria Antonietta Perna (@antonietta)
on CodePen.

Here's the generated code in place on the original demo:

The post 5 Super CSS Grid Generators for Your Layouts appeared first on SitePoint.

Mobile Attribution 101: What Every Developer Needs to Know

Aug 5, 2019

Description:

Mobile Attribution 101: What Every Developer Needs to Know

This article was created in partnership with StudioWorks. Thank you for supporting the partners who make SitePoint possible.

Optimizing the user experience of your app is crucial for its success, and the best way to do so is by collecting data on how users interact with it. While regular analytic tools do a good job, there’s an even better way now.

Welcome to mobile attribution. This approach to measuring app performance allows you to discover where and how users are interacting with your app and connect them with key points in the app journey.

But what exactly is mobile attribution and how do you use it? Keep reading to learn.

Mobile Attribution Explained

Mobile attribution is the process of measuring two metrics, such as ad spend and app installs. Given that the mobile advertising industry will exceed $244 billion by 2020, you need to know which strategies and channels are wasting your money or generating the most returns.

Mobile attribution also helps mobile app developers and companies determine how users are interacting with apps and mobile ads. This information can then be used to optimize marketing campaigns, the user experience of an app, and more.

In a nutshell, the process looks like this:

How mobile attribution works: user clicks ad; user ID saved to network; user installs app; user opens app; attribution SKD launches; attribution tool collects dataHow mobile attribution works

Not taking advantage of mobile attribution means that you won’t have the most detailed and accurate data on your mobile app and its advertising performance. This can result in missing opportunities when they arise, or discovering problems too late.

Appsflyer: people-based attribution. One view of all devices, platforms and channelsAppsflyer is a market leader in ad attribution and analytics with their proprietary “People-based Attribution” technology

Next, let’s talk more about why you should be using mobile attribution.

The Benefits of Mobile Attribution

These are some of the main benefits you will experience by taking advantage of mobile attribution.

Track user events to optimize your app

You will be able to track every little detail of how users interact with mobile ad campaigns in your app. This includes where they found your app originally, which pages they navigate to, and what features they interact with the most.

This information is priceless. It’s telling you exactly what pages and features users enjoy the most, which channels drive the most traffic, and what campaigns are generating the most results for your app.

You can then invest more capital into profitable channels, push favorite features to the forefront, and improve how every user engages with your application.

The post Mobile Attribution 101: What Every Developer Needs to Know appeared first on SitePoint.

SitePoint Premium New Releases: Smashing 6 + GraphQL & React Native

Aug 2, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Smashing Book 6: New Frontiers In Web Design

It’s about time to finally make sense of all the front-end and UX madness. Meet Smashing Book 6, with everything you need to know about web design. From design systems to accessible single-page apps, CSS Custom Properties, CSS Grid, Service Workers, performance patterns, AR/VR, conversational UIs and responsive art direction.

➤ Read Smashing Book 6: New Frontiers In Web Design.

Working with GraphQL and React Native

In this tutorial, we’re going to demostrate the power of GraphQL in a React Native setting by creating a simple coffee bean comparison app. So that you can focus on all of the great things GraphQL has to offer, Jamie has put together the base template for the application using Expo.

➤ Read Working with GraphQL and React Native.

And More to Come…

We're releasing new content on SitePoint Premium regularly, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Smashing 6 + GraphQL & React Native appeared first on SitePoint.

Master Modern JavaScript with This Curated Reading List

Jul 31, 2019

Description:

Are you daunted by the complexity of the JavaScript ecosystem? Are you still writing ES5, but looking for an opportunity to embrace modern standards? Or, are you confused by the explosion of frameworks and build tools, and unsure what to learn first? Fear not, here are my handpicked selection of books from SitePoint Premium, intended to help you well on your way to mastering modern JavaScript.

JavaScript: Novice to Ninja, Second Edition

I've placed this book at the top of my list, as it has something for almost everybody. It starts by covering the fundamentals (and thus serves well as a desk reference), then moves on to tackle more advanced topics, such as testing and functional programming.

The second edition has been updated to cover ECMAScript 6 and does a great job of introducing you to its more common features. You also get to put your newly acquired knowledge into practice at the end of each chapter, as you build out a quiz app, adding features as you move through the book. I really like this project-based approach to learning and think it is one of the better ways to advance your programming skills.

For those who just want to dip, I'd recommend reading the Modern JavaScript Development chapter. This will bring you up-to-date with many of the recent developments, such as working with modules, and the hows and the whys of transpiling your code.

Read the book

Practical ES6

This anthology picks up where Novice to Ninja left off and allows you to dive deeper into many of the newer additions to the JavaScript language. It covers much of the basic syntax (e.g. const, let, arrow functions, etc...), and offers a great way to get up to speed in a particular area.

There are also more in-depth articles on topics such as ES6 classes and ES6 modules, as well as a look at what came down the pipeline in ES2017 and ES2018. And if you're starting to get confused about what all these version numbers mean, we've got you covered. The anthology packs a chapter on JavaScript versioning and the process of deciding what gets added to the language.

Read the book

A Beginner's Guide to npm - the Node Package Manager

npm is a package manager for JavaScript, similar to PHP's composer, or Perl's CPAN. It allows you to search an online database of packages (a.k.a. the registry) and install them on your machine. The npm registry is vast — containing over 600,000 packages — and I think it is fair to say that it has revolutionized the way JavaScript developers collaborate with each other.

This short book from our Developer Essentials series has made the list because npm is something you cannot ignore if you are serious about writing JavaScript in 2019. The guide walks you through getting npm installed and configured (which can sometimes be a tad tricky) and using it effectively in your day-to-day work. If you're going to learn just one JavaScript tool in 2019, make it npm. You'll encounter it in tutorials everywhere and it is the standard delivery mechanism for almost any modern JavaScript library out there.

Read the book

JavaScript: Best Practice

Now that we've had a look at the basics, it's time to kick it up a notch with some JavaScript best practices. This anthology is full of tips and tricks to help you write modern JavaScript that is performant, maintainable, and reusable. It's hard to pick favorites from so many great titles, but there are two articles that stand out.

The Anatomy of a Modern JavaScript Application takes a good look at how to build a JavaScript application in 2019. It covers everything from application architecture to deployment and will help you to order many of the concepts and buzzwords you may have heard floating about.

Flow Control in Modern JavaScript introduces you to a variety of strategies for dealing with asynchronous JavaScript in a modern code base. It looks at one of my favorite additions to the language — async await — and dispels the myth that writing a JavaScript web app will automatically land you in callback hell.

Read the book

Node.js Web Development, Fourth Edition

No journey through modern JavaScript would be complete without a look at how to run it on the server. And this book gives you an excellent starting point, bringing you straight to the heart of developing web applications with Node.js.

As you follow along you'll build and iterate on a note taking app. This will form the basis for learning all about real-time applications, data storage, user authentication, deployment with Docker and much more. And even if server-side development isn't your thing, I'd still recommend reading the first couple of chapters. These will give you a good idea where Node fits in to today's JavaScript landscape.

Read the book

The Versioning Guide to Modern JavaScript

To finish we have The Versioning Guide to Modern JavaScript, which is really a large collection of links taken from the much-missed Versioning newsletter. I've included this, as there's so much going on in the world of modern JavaScript development, that I've barely been able to scratch the surface here. I'm confident that this guide will offer you a wealth of ideas and inspiration on what to dig into next.

Read the book

And that's a wrap. I hope this curated list goes some way to helping you navigate the choppy waters of modern JavaScript development.

The post Master Modern JavaScript with This Curated Reading List appeared first on SitePoint.

An Introduction to Data Visualization with Vue and D3.js

Jul 30, 2019

Description:

An Introduction to Data Visualization with Vue and D3.js

Web applications are normally data-driven and oftentimes the need arises to visualize this data. That’s where charts and graphs come in. They make it easier to convey information, as well as demonstrate correlations or statistical relationships. Information presented in the form of a chart or a graph is also easier for a non-native speaker to understand.

In this tutorial, we’ll learn how to visualize data in a Vue project. For this, we’ll be using the popular D3.js library, which combines powerful visualization components and a data-driven approach to DOM manipulation.

Let’s get started.

Note: the code for this tutorial can be found on GitHub.

What is D3?

As you can read on the project’s home page, D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. Its emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework.

Whereas most people will refer to D3.js as a data visualization library, it’s not. D3 is more of a framework comprising different parts — such as jQuery parts (which help us select and manipulate DOM elements), Lodash parts, animation parts, data analysis parts, and data visualization parts.

In this tutorial, we’ll be working with the visualization aspect of D3. The real meat of D3 when visualizing data is:

the availability of functions for decorating data with drawing instructions creating new drawable data from source data generating SVG paths creating data visualization elements (like an axis) in the DOM from your data and methods What We’ll Be Building

We want to create an app that lets users search for a repo on GitHub, then get a visual representation of issues opened in the past week that are still open. The end result will look like this:

Final Chart

Prerequisites

This tutorial assumes you have a working knowledge of Vue. Previous knowledge of D3.js isn’t required, but if you’d like to get up to speed quickly, you might want to read our D3 by example tutorial.

You’ll also need to have Node installed on your system. You can do this by downloading the binaries for your system from the official website, or using a version manager.

Finally, we’ll be using the following packages to build our app:

Vue CLI — to scaffold out the project D3.js — to visualize our data Lodash — which provides a handful of utility methods Moment JS — for date and time formatting axios — an HTTP client to help us make requests to an external API New Vue Project

I prefer creating new Vue projects using Vue CLI. (If you’re not familiar with Vue CLI, our beginner’s guide in this Vue series gives a full introduction.) Vue CLI provides a nice folder structure for placing different sections of the code, such as styles, components, and so on.

Make sure that the CLI is installed on your machine:

npm install -g @vue/cli

Then create a new project with the following command:

vue create issues-visualization

Note: while creating a new project using Vue CLI, you’ll be prompted to pick a preset. For this particular project, we’ll just stick with the default (Babel + ESLint).

Once our new Vue project has been created, we cd into the project folder and add the various node modules we’ll need:

npm install lodash d3 axios moment

Even though this is a simple app that doesn’t have many running parts, we’ll still take the components approach instead of dumping all the code inside the App.vue file. We’re going to have two components, the App component and a Chart component that we’re yet to create.

The App component will handle fetching data from GitHub, then pass this data to the Chart component as props. The actual drawing of the chart will happen inside the Chart component. Structuring things this way has the advantage that, if you want to use a library other than axios to fetch the data, it’ll be easier to swap it out. Also, if you want to swap D3 for a different charting library, that’ll be easier too.

Building the Search Interface

We’ll start by building a search interface that lets users enter the name of the repo they want to see visualized.

In src/App.vue, get rid of everything inside the <template> tag and replace the content with this:

<template> <div id="app"> <form action="#" @submit.prevent="getIssues"> <div class="form-group"> <input type="text" placeholder="owner/repo Name" v-model="repository" class="col-md-2 col-md-offset-5" > </div> </form> </div> </template>

Here we have a form which, upon submission, prevents the browser’s default submission action, then calls a getIssues method that we’re yet to define. We’re also using a v-model directive to bind the input from the form to a repository property inside the data model of our Vue instance. Let’s declare that property repository as an empty string. We’ll also add a startDate property, which we’ll later use as the first date in our time range:

import moment from "moment"; import axios from "axios"; export default { name: "app", data() { return { issues: [], repository: "", startDate: null }; }, methods: { getIssues() { // code goes in here } } };

Now on to creating the getIssues method:

getIssues() { this.startDate = moment() .subtract(6, "days") .format("YYYY-MM-DD"); axios .get( `https://api.github.com/search/issues?q=repo:${this.repository}+is:issue+is:open+created:>=${this.startDate}`, { params: { per_page: 100 } } ) .then(response => { const payload = this.getDateRange(); response.data.items.forEach(item => { const key = moment(item.created_at).format("MMM Do YY"); const obj = payload.filter(o => o.day === key)[0]; obj.issues += 1; }); this.issues = payload; console.log(this.issues); }); }

In the above block of code, we start by setting the startDate data property to six days ago and formatting it for use with the GitHub API.

We then use axios to make an API request to GitHub to get all issues for a particular repository that were opened in the past week and that are still open. You can refer to GitHub’s search API if you need more examples on how to come up with query string parameters.

When making the HTTP request, we set the results count to 100 per page (the max possible). There are hardly any repositories with over 100 new issues per week, so this should be fine for our purposes. By default, the per_page value is 30.

If the request completes successfully, we use a custom getDateRange method to initialize a payload variable that we will be able to pass to the Chart component. This payload is an array of objects that will like so:

[ {day: "Dec 7th 18", issues: 0}, {day: "Dec 8th 18", issues: 0}, {day: "Dec 9th 18", issues: 0}, {day: "Dec 10th 18", issues: 0}, {day: "Dec 11th 18", issues: 0}, {day: "Dec 12th 18", issues: 0}, {day: "Dec 13th 18", issues: 0} ]

After that, we iterate over the API’s response. The data we’re interested in is in an items key on a data property on the response object. From this, we take the created_at key (which is a timestamp) and format it as the day property in our objects above. From there, we then look up the corresponding date in the payload array and increment the issues count for that date by one.

Finally, we assign the payload array to our issues data property and log the response.

Next, let’s add in the getDateRange method:

methods: { getDateRange() { const startDate = moment().subtract(6, 'days'); const endDate = moment(); const dates = []; while (startDate.isSameOrBefore(endDate)) { dates.push({ day: startDate.format('MMM Do YY'), issues: 0 }); startDate.add(1, 'days'); } return dates; }, getIssues() { ... } }

Before we get to the visualization bit, let’s also log any errors we might encounter when making our request to the console (for debugging purposes):

axios .get( ...) .then(response => { ... }) .catch(error => { console.error(error); });

We’ll add some UX for informing the user in the case that something went wrong later.

So far, we have an input field that lets the user enter the organization/repository name they wish to search issues for. Upon form submission, all issues opened in the past one week are logged to the console.

Below is an example of what was logged on the console for the facebook/react repo:

Console output

If you start up the Vue dev server using npm run serve and enter some different repos, you should see something similar. If you’re stuck for inspiration, check out GitHub’s Trending page.

Next comes the fun bit — visualizing this data.

Drawing a Bar Chart Using D3

Earlier on, we mentioned that all the drawing will be handled inside a Chart component. Let’s create the component:

touch src/components/Chart.vue

D3 works on SVG elements, and for us to draw anything with D3, we need to have an SVG element on the page. In our newly created component (src/components/Chart.vue), let’s create an SVG tag:

<template> <div> <svg></svg> </div> </template>

For this particular tutorial, we’ll visualize our data using a bar chart. I picked a bar chart because it represents a low complexity visual element while it teaches the basic application of D3.js itself. The bar chart is also a good intro to the most important D3 concepts, while still having fun!

Before proceeding, let’s update our App component to include the newly created Chart component below the form:

<template> <div id="app"> <form action="#" @submit.prevent="getIssues"> ... </form> <chart :issues="issues"></chart> </div> </template>

Let’s also register it as a component:

import Chart from './components/Chart.vue'; export default { name: "app", components: { Chart }, ... }

Notice how we’re passing the value of the issues data property to the Chart component as a prop:

<chart :issues="issues"></chart>

Let’s now update our Chart component to make use of that data:

<script> import * as d3 from "d3"; import _ from "lodash"; export default { props: ["issues"], data() { return { chart: null }; }, watch: { issues(val) { if (this.chart != null) this.chart.remove(); this.renderChart(val); } }, methods: { renderChart(issues_val) { // Chart will be drawn here } } }; </script>

In the above code block, we’re importing D3 and Lodash. We then instantiate a chart data property as null. We’ll assign a value to this when we start drawing later on.

Since we want to draw the chart every time the value of issues changes, we’ve created a watcher for issues. Each time this value changes, we’ll destroy the old chart and then draw a new chart.

Drawing will happen inside the renderChart method. Let’s start fleshing that out:

renderChart(issues_val) { const margin = 60; const svg_width = 1000; const svg_height = 600; const chart_width = 1000 - 2 * margin; const chart_height = 600 - 2 * margin; const svg = d3 .select("svg") .attr("width", svg_width) .attr("height", svg_height); }

Here, we set the height and width of the SVG element we just created. The margin attribute is what we’ll use to give our chart some padding.

D3 comes with DOM selection and manipulation capabilities. Throughout the tutorial, you’ll see lot’s of d3.select and d3.selectAll statements. The difference is that select will return the first matching element while selectAll returns all matching elements.

The post An Introduction to Data Visualization with Vue and D3.js appeared first on SitePoint.

The Strategic Advantages of Headless Web Design

Jul 29, 2019

Description:

How Your Agency Can Use Headless Web Design as a Strategic Advantage

This article was created in partnership with Duda. Thank you for supporting the partners who make SitePoint possible.

Kentico’s most recent State of the Headless CMS report claims that the concept of the headless content management system is “becoming the industry standard for future-proofing and streamlining content creation.” In fact, the report estimates that by this summer, headless CMS use will have doubled.

But what does that even mean?

If you’re currently using a traditional CMS such as WordPress, Drupal or Joomla for your web development needs, chances are you may have never heard of a headless CMS. But what you might know is that you want to build a one-of-a-kind website for your growing agency that can scale with ease, and that marketing your brand across multiple channels is a must if you want to beat the competition.

In this article, we’re going to share with you what the headless CMS trend is all about and how using this API-powered approach to design and deploy your company’s website can help you get ahead, no matter how competitive your industry is.

So, let’s get started.

What Is a Headless CMS?

To better understand what a headless CMS is, let’s compare a traditional CMS (or “monolithic”, as developer Bret Cameron likes to call it), a decoupled CMS, and a headless CMS.

Image source Traditional CMS

Traditional CMS platforms like WordPress link the front end of your website, called the head, to the back end of your site, where all your content files and databases are stored. The head of the CMS is strictly responsible for presenting your website to site visitors when they click on your site. The back end, on the other hand, not only stores content, but is where website design and customization applications are stored, where content is created, and where management of site functionality occurs.

Paired together, as they traditionally are, the back-end portion of the website relies on the head of the CMS to display the stored content on devices to users.

Decoupled CMS

With a decoupled CMS architecture, the head portion and the back end of the site are split into two separate systems. One system is responsible for content creation and storage, and the other is responsible for presenting the data to users on an interface, such as a website, mobile app, smartwatch, etc.

When content is created on your website using a headless CMS, a RESTful API helps connect the back end to the head, so that the content can be delivered to users on any device or channel with ease.

A RESTful API is a type of application interface using HTTP requests to GET, POST, PUT, and DELETE data that’s requested by users. It allows for multiple data formats such as JSON, HTML, XML, and plain text. It’s ultimately what links the client and server in a decoupled CMS, allowing your site to infinitely scale and deliver content to anyone on any device.

Headless CMS

A truly headless CMS eliminates the head portion altogether, leaving just the back end. In other words, there’s no dedicated system for front-end presentation. And while you might initially wonder if this type of structure might be to your disadvantage, it’s actually the best way to display content to your site visitors on all devices and interfaces, putting your agency in the best possible position to scale.

Here’s a simple breakdown of how it works:

Website owners create content (often in small blocks) in the headless CMS, with no regard for how it will display to users. They also store and manage this content here. An API connects the back end to many different channels and the various engines that power their front ends. The channel or device displays your site’s content.

The way your content will display on the different channels and devices will depend on the frameworks and tools your front-end developers use to act as the “head” portion of your headless CMS.

So it’s more freedom to integrate with more front ends, more scalably and without the risk of breaking anything. How, exactly? Let’s dive a little deeper.

The Advantages of a Headless CMS

APIs work with a headless CMS to do the following:

Reduce Strain. Using a headless CMS, which stores content in a cloud repository as opposed to a server, will leverage less bandwidth, save resources, and reduce the strain your clients’ websites experience.
 Manage and Store Content
.
With a headless CMS, all content, including written text and images, are stored in the back end of the database. With a traditional CMS, not only is content stored and managed here, but so are front-end templates, CSS, and plugins for front-end functionality. Separating the back end from the front end means you can upgrade and customize your website without compromising site speed or performance — since all your client needs to worry about is managing and storing content. Third-party Integrations.

A headless CMS gives you the chance to use third-party systems to trigger, write and read content for you, making development less disruptive. It also gives developers the flexibility to use the front-end framework they prefer to display their site content, focusing more on content creation and less on content management.

Lastly, a headless CMS protects you, your company and your website’s content from future technological advances. After all, platforms and technology are always evolving, making it challenging to keep up.

For example, think about all the problems that those of us who didn’t build responsive websites had when mobile-friendliness became a necessity. People all over, regardless of how well-established and successful they were at the time, had to change everything to ensure a seamless mobile experience.

And there’s no end in sight to the trends — from artificial intelligence to augmented reality to voice assistants — that have the power to change the way you build and deliver digital content experiences. Traditional CMS platforms were designed with website publishing in mind. They were not built with social media product listings, smartwatch apps or talking speakers in mind.

So when the build is decoupled from the delivery, you’re in the best possible position to experiment with new channels and formats on an agile basis. And this is a key aspect to any agency’s value proposition.

If you take advantage of the headless CMS approach and use APIs to deliver your content to where it needs to surface, it won’t matter what changes. That’s because as long as an API-fed front end can be built, your client’s content can be configured to render properly.

Headless CMS Limitations

Though it might seem as though a headless CMS is the answer to all your website problems, be aware that there are some downsides preventing traditional CMS users from making the switch:

Limited Editing UI.

When compared to traditional CMSs, headless CMSs usually lack the flexibility that content managers generally rely on to optimize the content for specific front end uses. If you need to use your CMS for creating landing pages or even article page layouts, the lack of a “Preview” button might be an issue. There is no WYSIWYG page editor on these platforms, since the whole point of going headless is that it won’t render HTML, which makes designing medium-specific content experiences more difficult.
 Lack of Built-in Features
.
 Boris Kraft, CTO and co-founder of Magnolia CMS, reminds people that a traditional CMS will generally come with features like “asset management, navigation, security, workflow, access control, caching, categorization and link management.” In fact, he goes on to say that while a headless CMS does provide companies with more flexibility, many often get lost in the hype and forget that “I have to write, debug and maintain everything I need myself” with a headless CMS solution.

While there is no CMS solution that satisfies all needs, it’s worth noting that the headless CMS approach can be beneficial when used in a hybrid situation.

In fact, if you use a solution such as Duda, a leading web design platform for companies providing web design services to others, and take advantage of APIs to deliver content and handle your site’s structure and layouts on multiple channels, you can get the best of both worlds.

The post The Strategic Advantages of Headless Web Design appeared first on SitePoint.

SitePoint Premium New Releases: React + React Native

Jul 26, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Get Started with React Native

For developers with a web background, frameworks such React Native allow you to create mobile apps with languages you’re already familiar with: HTML, XML, CSS, and JavaScript. This guide will help get you up and running with React Native.

➤ Read Get Started with React Native.

Build Your Own React Universal Blog App

An introductory course to building your first universal React app. Starting with an introduction to React, and then getting familiar with the invaluable React toolkit - Create React App, we'll then walk you through the steps of creating a universal React blog app from scratch.

➤ Read Build Your Own React Universal Blog App.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: React + React Native appeared first on SitePoint.

A Beginner’s Guide to Feathers.js

Jul 25, 2019

Description:

A Beginner's Guide to Feathers

In this article, you’ll learn how to build a RESTful API Server in Node.js using Feathers.

An API server, also known as an Application Server, is a program that provides data to front-end applications. It also handles business logic in the back end and provides restricted access to an organization's database. It doesn't just prevent unauthorized persons from accessing the data; it can also restrict logged-in users from accessing or altering data if they don't have permission to do so.

Every application you build will need to provide a service to its end users. For that, your application will need data to process. You can use remote APIs to create a new service. For most applications, though, you’ll need to manage your own data store. A popular option is to use online data storage services such as Firebase. This way, you don't have to deal with the nitty gritty details of running a distributed database server. However, your project needs may require the use of a full-fledged, in-house database management system such as MongoDB or Oracle. For your front-end application to access the data stored in the database, you’ll need a server application that sits between the database and the front-end application.

architecture

As illustrated in the diagram above, the work of an application server is to access data from a database using SQL or NoSQL commands and convert into a format that front-end applications (client browser) can understand — such as JSON. In addition, the application server can use various security protocols — such as HTTPS encryption and token authorization — to ensure that communication between the database and the client application is safe and secure. One main advantage of using such an architecture is that you can deploy applications that target different platforms — desktop, mobile, web, and so on — using the same application server. It’s also very easy to scale your application horizontally in order to serve more users efficiently with fast response times.

We’re going to build a simple API server and demonstrate the various features that Feathers provides.

Prerequisites

Before you begin following this tutorial, you’ll need to have a good foundation in the following topics:

ES6 JavaScript creating Express apps creating RESTful APIs with Express

Feathers is built on top of Express, a minimalist web framework for Node.js. If you’ve completed the tutorials demonstrated in the links, you’ll realize that it's quite tiring building RESTful APIs using just Express. With Feathers, most of the repetitive work is already done for you. You only need to focus on configuring and customizing code. Let's dive into the code and learn how this web framework works.

Project Creation

To get started with Feathers, you’ll need to install its command line application globally:

npm install -g @feathersjs/cli

Next, create a new API project using the commands below:

mkdir contacts-api cd contacts-api feathers generate app

Below are the options I chose. Feel free to choose any testing framework. Unfortunately, testing is beyond the focus of this article, so it won't be covered here. Personally, I like simplicity, and that’s why I went with Jest.

Creating a Feathers app in the command line

Once the installation is complete, you can open you favorite code editor to look at the project files.

Project structure, as seen in a code editor

If you’ve completed the Express tutorials I listed in the prerequisites section, you shouldn't be intimidated by the generated code. Here's a brief summary that describes the folders and files.

The created files

Don't be too concerned with what each file does right now. You’ll come to understand how they work in the course in this tutorial. For now, let's confirm that the tests are working.

Linting

To ensure our project is compliant with the defined ESLint rules, just run the command npm test. If you’re on a Unix or Linux platform, this should run fine. If you’re on Windows, there are few things you need to adjust for the tests to run successfully.

First, go to package.json and look at the scripts section. Change the test line to this:

"scripts": { "test": "npm run eslint && SET NODE_ENV= npm run jest", },

Next, if you’ve installed Prettier in Visual Studio Code, you'll need to change the single quote setting to true in the Workspace settings tab:

{ "prettier.singleQuote": true }

Finally, make sure that, when you create or edit any file, the line ending is LF. If you’re using Visual Studio Code or a similar editor, you can check the current line ending style at the status bar. If it says CRLF, change to LF. Making those changes will help you pass the lint tests. Unfortunately, to make the tests pass will require a bit more work, which won't be covered here.

Let's look at how we can generate a CRUD RESTful interface.

Generate Service

Building a Restful CRUD API interface in Express requires a bit of work. In Feathers, all you have to do is execute a single command, answer a few questions and have the code generated for you:

$ feathers generate service ? What kind of service is it? NeDB ? What is the name of the service? contacts ? Which path should the service be registered on? /contacts ? What is the database connection string? nedb://../data force config\default.json create src\services\contacts\contacts.service.js force src\services\index.js create src\models\contacts.model.js create src\services\contacts\contacts.hooks.js create test\services\contacts.test.js

We’ll be using NeDB database for this tutorial. Feathers does support both SQL databases such as MySQL and NoSQL databases such as MongoDB. However, installing a database system — whether on your machine or on a cloud server — requires a certain amount of time configuring it. NeDB, on the other hand, is an in-memory database that’s 100% JavaScript and supports a subset of MongoDB API. There’s no configuration needed; you just install it. It's a great database for prototyping and testing new applications. This is what we’ll use in this tutorial.

Let's briefly look at some of the files that have been generated using this command:

services/contacts/contact.service.js. This is a Feathers service that provides the CRUD API endpoints for /contacts. Pretty small, isn't it? This is because Feathers does the heavy lifting for us. It saves us from writing boilerplate CRUD code.

services/contacts/contact.hooks.js. This is where we customize how the CRUD logic behaves. We have the before section, where we can check or change data before Feathers reads or writes to the database. We also have an after section, where we can check or change the results from the database before it’s sent to the client application. We can do things like restricting access, data validation, performing join operations and calculating values for additional fields or columns.

models/contacts.model.js. This where we define a model and attach it to a database table. This is also where we define a schema which can be used to validate fields when a new record is inserted or updated. Unfortunately, NeDB doesn’t support schemas. However, I've provided an example of a model that’s connected to MongoDB, which supports the schema feature via the mongoose adapter:

"use strict"; const mongoose = require("mongoose"); const Schema = mongoose.Schema; require("mongoose-type-email"); const contactsSchema = new Schema({ name: { first: { type: String, required: [true, "First Name is required"] }, last: { type: String, required: false } }, email: { type: mongoose.SchemaTypes.Email, required: [true, "Email is required"] }, phone: { type: String, required: [true, "Phone is required"], validate: { validator: function(v) { return /^\+(?:[0-9] ?){6,14}[0-9]$/.test(v); }, message: "{VALUE} is not a valid international phone number!" } }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now } }); const contactsModel = mongoose.model("contacts", contactsSchema); module.exports = contactsModel;

Despite the limitations of using NeDB, it’s still a great database for prototyping. Most NoSQL databases will allow you to submit data using any structure without having to define a schema first. It’s wiser to implement a schema once the project requirements have been realized. With a schema in place, Feathers will perform field validation for you using the rules you’ve defined. You'll need a production-ready database such as MongoDB to be able to define a schema. Do note the configuration for the development database is defined at config/default.json:

"nedb": "../data"

This is where database credentials are provided. We also have another config file called config/production.json. This is the production database configuration that’s used when you deploy your Feathers app. It's important to use a separate database during development. Otherwise, you run the risk of deleting or corrupting business operational data on the production database.

Now that we have our CRUD service for contacts set up, it's time to take it for a spin. You can start the Feather server using the command npm start. Do note that this server doesn’t support hot reloading. So you'll need to restart it every time you make a change to the code. In order to interact with our Feathers app, we’ll need an API browser tool such as Postman or Insomnia. I'll be using Insomnia in this tutorial, but you can follow along easily with Postman or any other tool.

Create a new GET request (press Ctrl + N) and give it the title “List Contacts”. In the URL section, enter http://localhost:3030/contacts. When you hit the Send button, you should have the following view:

Listing contact requests: the view in your code editor after hitting the Send button

Nothing! Our database is currently empty, so we need to create some new contacts. Create a new request called Create Contact. Fill in the rest of the fields as shown below:

Form for creating the new contact

In case you forgot to change the METHOD to POST in the above form, you can do so later. Change the method to POST and change the Body tab to JSON. Copy the following data in the JSON tab:

{ "name": { "first": "Jack", "last": "Bauer" }, "email": "jack@ctu.mail", "phone": "+1234567" }

When you hit the Send button, you should get the following response. Notice that an _id has been generated for your new contact.

Response with new ID

Go back to List Contacts and hit the Send button again. You should get the following result:

{ "total": 1, "limit": 10, "skip": 0, "data": [ { "name": { "first": "Jack", "last": "Bauer" }, "email": "jack@ctu.mail", "phone": "+1234567", "_id": "ybnRxL6s2QEGhj4i" } ] }

Go back to Create Contact and post a couple of new records:

{ "name": { "first": "Chloe", "last": "O'Brian" }, "email": "chloe@ctu.mail", "phone": "+1987654" } { "name": { "first": "Renee", "last": "Walker" }, "email": "renee@fbi.mail", "phone": "+150505050" }

Let's now perform an update. For this, we won't use the UPDATE HTTP method. This method will completely overwrite a record. What we want to do is just overwrite a single field, not the the whole record. For that, we’ll use PATCH. Create a new request, Update Contact as illustrated below:

Updating a contact

In the URL field, put http://localhost:3030/contacts/{_id}. Replace {_id} with the ID of the first record. Place the following data into the JSON tab:

{ "email": "jack.bauer@gmail.com" }

Hit the Send button. You should get the following result:

08-Patch-Jack-Email

Notice how the the rest of the fields remain intact. Next, we’re going to delete a record. This one is easy. Just create a new DELETE request and name it Delete Contact. In the URL field, use the format http://localhost:3030/contacts/{_id}. Just like before, replace {_id} with the ID of the record you want to delete. Hitting Send will delete that record for you. You can confirm by running the List Contact request again.

We've just verified that all CRUD operations are running okay. In the next section, we’ll learn how to set up authentication.

The post A Beginner’s Guide to Feathers.js appeared first on SitePoint.

The Best Web Hosting Providers For Your Needs

Jul 25, 2019

Description:

Hosting Providers: A Comparison

In this article, we're going to dive into the offerings of the most prominent players in the hosting industry, and wade through their plans, infrastructure, and reputation among users, to give you recommendations for the best hosting provider for your needs.

We divided hosting vendors into three categories:

general-purpose shared hosting providers WordPress — specialized premium providers, and unmanaged, dedicated server solutions General-purpose Shared Hosting Providers

This category covers the widest part of the hosting market — from the entry-level shared plans to prosumer and premium offerings with dedicated resources and different levels of support.

A2 Hosting

A2 Hosting home page

A2 Hosting was founded in 2003 in Michigan, USA. They offer entry-level shared hosting packages, managed VPS and dedicated servers and seller hosting.

Their shared packages are standard cPanel packages, with SSD-based storage and a promise of reserved CPU and RAM resources — even with the smallest of plans.

Their LITE plan begins at $2.96 per month, which allows for one website. Their SWIFT plan has unlimited websites, starting with $3.70 per month. And their TURBO plan starts at $7.03 per month. These prices are — as the A2 website claims — a 63% discount.

They offer free migration, 24/7 support, DDOS protection and “99.99% uptime commitment”, which is always nice to know.

A2 developer features

The flagship plan that distinguishes A2 is the TURBO package, which uses LiteSpeed servers — an excellent replacement for Apache, which also brings with it a performance edge.

Underlying LiteSpeed allows A2 to offer QUIC as an experimental feature on the TURBO plan.

A2 offers four possible server locations — two data centers in the US, one in Singapore and one in Amsterdam, so they'll have you covered in most parts of the world.

For more details check out their website.

SiteGround

SiteGround home page

SiteGround is a “holding of companies registered in the USA, UK, Bulgaria, and Spain that manages four offices and several datacenter locations around the world”. Established in 2004, it has become somewhat of an institution in the hosting world that’s been recommended by WordPress itself.

SiteGround’s hosting range is similar to A2’s, and starts from the entry-level shared packages all the way to cloud products and dedicated servers. The company also offers bespoke enterprise solutions.

SiteGround offers packages similar to A2’s plans — although its GrowBig and GoGeek plans cost a bit more than a comparable A2 plans.

SiteGround plans

However, SiteGround does offer free daily backups across all the plans, free migration on GrowBig and GoGeek — as well as staging installation, which is handy for more professional setups.

Use of resources for each plan is limited in terms of server processes, simultaneous connections, CPU seconds, RAM, cronjob intervals — and they are specific and transparent about it, which is a plus.

One caveat to note is that the prices mentioned above are promotional prices for the first year of signup, and renews at a higher price after that.

SiteGround's server stack consists of NGINX as a caching solution in front of Apache — which means that even SiteGround's StartUp plan is not constrained by Apache limitations.

Screenshot of a Facebook reply from SiteGround

We use NGINX as a reverse proxy for caching, standing in front of an Apache server. This means that cached results get zero latency from the web server, PHP or MySQL services. The content comes our directly from the server's memory. It's as if you're fetching an HTML file — mostly networking between you and the server, and of course the size of your content. — Hristo Pandjarov

They offer server locations in the UK, USA, continental Europe and Asia (Singapore).

SiteGround has also recently announced support for the QUIC next-generation protocol, which will increase site loading speed even if there’s poor internet connectivity at your location.

For more details check out their website.

Bluehost

Bluehost was founded by Matt Heaton in 2003, and enjoyed immense popularity until 2011, when it was acquired by EIG. Since the acquisition, it has remained one of the most prominent players in the hosting scene, but it has been plagued by mixed reviews regarding its user experience.

Bluehost home page

Bluehost offers a similar range of products to the others — from entry-level shared plans to VPS, dedicated servers, ecommerce and WordPress packages. But it currently offers the lowest prices of the three mentioned in this category (for a 36-month term; prices go up as you'd expect for shorter terms).

Bluehost packages

All but the smallest of these plans include unlimited resources (SSD Storage). However, do note that in the fine print of their Terms of Service notes:

While rare, we occasionally constrain accounts utilizing more resources than should be the case in the normal operation of a personal or small business website.

Negative Bluehost facebook post

Hosting Recommendations Please

We're looking for fast, reliable + scalable hosting for 100+ WordPress sites (of varying sizes) with WHM + cPanel.

Been migrating to Bluehost Dedicated server and it's just not cutting it. Support is slow and the server has been dropping in and out over the past 24 hours + turns out the resources are capped (despit what “sales” said).

“No specified limits to resources” in this case may translate to “no guaranteed resources”. Even before the EIG acquisition, Bluehost had introduced a CPU-throttling strategy — so be warned. You can read more about Bluehost's restrictions regarding resources here.

On its bigger plans, Bluehost offers SSH access, cron jobs, daily backups etc. But it’s mostly oriented toward the entry-level market.

Bluehost has some perks and a custom management web UI for WordPress customers.

As for the server locations — Bluehost doesn’t offer straightforward information, but besides Utah, USA, they seem to have data centers in China and India (Mumbai).

The post The Best Web Hosting Providers For Your Needs appeared first on SitePoint.

10+ Top Vue.js Tools & Libraries

Jul 23, 2019

Description:

Vue continues to grow in popularity and is rapidly being adopted by many developers, and Vue.js tools are popping up everywhere. This is not without reason: Vue's shallow learning curve, clear functionality-driven structure, and excellent documentation make it easy for novices to pick it up, and for more experienced developers to make a switch from other frameworks like React or Angular.

If you are serious about Vue development, sooner or later you'll meet some fundamental tools and libraries which stand out from the crowd. Using them will level up your career as a Vue developer, and make you feel like a professional.

I've compiled a list of the most notable tools and libraries you should know and eventually use in your Vue.js projects. Unlike many other articles out there, which list only UI component libraries, this compilation explores a much broader mixture of tools, libraries, and plugins in the Vue ecosystem.

I've selected these based on their usefulness, effectiveness, and uniqueness — not their GitHub popularity or star ratings.

Enough talk: here they are, the top ten.

Vue CLI

It seems that having some kind of CLI tool is a must for every JavaScript application framework these days. Vue is no exception. Vue CLI is a fully-featured set of tools for rapid Vue development. Besides the usual project scaffolding, it allows you to experiment with new ideas even without creating a full project, by using its instant prototyping feature.

By default, Vue CLI offers support for the major web development tools and technologies, such as Babel, TypeScript, ESLint, PostCSS, PWA, Jest, Mocha, Cypress, and Nightwatch. This is possible thanks to its extensible plugin system. This means the community can build and share reusable plugins for common needs.

But the icing on the cake is the powerful GUI (Vue UI, which comes with the CLI) which allows you to create your project easily, and then configure and manage it along the way without the need for ejection.

Vue CLI

VuePress

The next big player in Vue's ecosystem is VuePress, a Vue-powered static site generator. Initially created as a tool for writing technical documentation, now it's a small, compact, and powerful headless CMS. Since version 1.x, it has offered great blogging features and a powerful plugin system. It comes with a default theme (tailored to technical documentation), but you can also build custom themes or use a pre-made option from the community.

In VuePress, you write the content in Markdown, which is then transformed to pre-rendered static HTML files. Once those files are loaded, your site runs as a single-page application powered by Vue, Vue Router and Webpack.

One of the main benefits of VuePress is that you can include Vue code or components within your Markdown files. This gives you great power and flexibility because you can develop your site almost like a regular Vue app, with all benefits that come from that.

VuePress

Gridsome

Gridsome has many similarities with VuePress but it takes a different and very powerful approach when dealing with data sources. It allows you to connect and use many different kinds of data in your app, which are then unified in one GraphQL layer. Basically, Gridsome uses Vue for front-end functionality and GraphQL for data management. The way this works can be summarized in the following three steps:

The post 10+ Top Vue.js Tools & Libraries appeared first on SitePoint.

How to Create Websites for Business Startups

Jul 23, 2019

Description:

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

Calling all web designers: We've got some good news for you.

New startups are appearing around the globe thanks to opportunities created through the new global economy. The good news is this:

New startups lead to a growing need for more business websites. In turn, this means more work for web designers.

These aren't isolated neighborhood businesses either. Their outreach is global and digital. They need websites that are optimized for conversions and flexible. So, here's your chance. You can serve these new entrepreneurs by creating great websites for them.

How do you go about it?

Below are 5 simple steps to create eye-catching, high-converting websites, with helpful examples.

5 Steps to Building Astonishing Business Startup Websites Step 1: Choose a mesmerizing color palette

There are 3 simple rules to follow when choosing a color palette for a business startup website:

You want a color palette that instantly attracts attention It needs to be on-brand It needs to visually support the message you're trying to get across

Over's bold color touches instantly attract attention.


This pre-built website, included in the Be Theme library, offers another example of an attention-grabbing color palette.


Forest does an excellent job at aligning its color palette with its brand — earth tones such as greens and browns are throughout. These palettes contribute to a visually memorable website.


FlightCard's subtle and cold color palette is a perfect choice for reinforcing its message: boarding passes have become so easy to use that you barely pay attention to them.

And if you're in need of a color palette that will appeal to a larger audience, BeApp2 can serve you perfectly well.

Step 2: Display crystal-clear product pics

This shouldn't be difficult to figure out. People want to know exactly what they are being offered. It has little to do with the color of the icons you're using.

A business startup has to present its products with flair and dignity. Its product pics need to give it an extra edge over huge businesses that have budgets to match.

Pennies proudly displays what its award-winning app looks likes on a smartphone. Just by looking at the page you can tell how easy it is to use and even figure out how the color codes work.

You can create a similar website with BeWallet. This pre-built website was designed from scratch for financial service startups. There's a huge audience of them in dire need of a better website.

Or, you could choose a more general pre-built website like BeSoftware to display a new business startup's crystal-clear pics.

JibJab takes things a step further. Its before and after approach is a persuasive and simple tactic to show what the startup offers.

Step 3: Show visitors how the startup serves them

The key here is to help visitors imagine themselves as actual customers by showing how the startup will serve them.

PeekCalendar has placed a video in the hero section. It shows how people can benefit from the new business.

BeApp3 allows you to incorporate product pics and a video to show how the new startup will benefit people using its products and services.

BePay has a Watch Video CTA button right above the fold that encourages your visitors to immediately view a product demo.

CutestPaw will soften up the hardest heart. Its entire how-to is cleverly rolled up into one single image: a hero shot showing how the new business will meet users' specific needs.

Step 4: Use whitespace

You can overuse whitespace, but often the more there is, the better. Whitespace is the #1 visual design element for a startup website. You want to be able to work with as much space as possible to highlight your main messages and product shots.

Tha Fly Nation's clean, airy design is pleasing to the eye and allows it to focus on the most important elements.

You can create a similar startup website with BeProduct4 or BeHosting2. These are pre-built websites where blank space is used to enhance user experience and emphasize the critical elements on the page.

SpellTower is perhaps the most extreme when it comes to whitespace. It is part of their brand and its minimalist design drives the message home.

Step 5: Design CTAs that grab users by the eyeballs

An easy-to-locate CTA button doesn't always cut it. If you want to convert visitors into users, you want a CTA button that's impossible to ignore – big, bright, and bold. It's so bright that a visitor feels compelled to click on it!

Wire's CTA button clearly stands out above the fold. It has a bold color, it's big enough to draw your attention once you've read the headline, and it's centered on the page so it acts as a "gate" that must be clicked to move forward.

BeERP uses the same bright-green button for its main CTA (the one you want your visitors to click). A secondary, plain button is to the right.

You can also direct attention to your CTA by having it match other elements on the page. A great example is BeKids. Here, the blue CTA button matches the visual elements in the hero section.

Conclusion

Follow these surefire steps so you can present your client with a website that is both eye-catching and built for conversion. Websites that feature stunning visuals and clever uses of white space create the kind of visitors a startup needs.

If you're fortunate to grab a good share of new business, you could easily find yourself overloaded. In this case, you can safely use websites that have been built from the ground up specifically for businesses.

You'll find the most generous gallery on Be Theme and its library of over 450+ pre-built websites to choose from. Pre-built websites you can customize to your liking.

These pre-built websites are functional, visually impressive, and feature interactive elements, stunning effects, and intuitive navigation. Simply personalize the one you select to fit your business or that of your client, and you're good to go!

The post How to Create Websites for Business Startups appeared first on SitePoint.

How to Build a Vue Front End for a Headless CMS

Jul 22, 2019

Description:

In this guide, we’ll learn how to build a modern blog website using Vue.js and GraphCMS, a headless CMS platform.

If you’re looking to start a quick blog today, my recommendation is to go straight to WordPress.

But what if you’re a media powerhouse and you want to deliver your content as fast as possible to multiple devices? You’ll probably also need to integrate your content with ads and other third-party services. Well, you could do that with WordPress, but you’ll come across a few problems with that platform.

You’ll need to install a plugin to implement additional features. The more plugins you install, the slower your website becomes. PHP is quite slow compared to most JavaScript web frameworks. From a developer’s perspective, it’s much easier and faster to implement custom features on a JavaScript-powered front end.

JavaScript offers superior performance to PHP in browser loading tests. In addition, modern JavaScript and its ecosystem provides a far more pleasant development experience when it comes to building new web experiences fast.

So there’s been a growth of headless CMS solutions — which are simply back ends for managing content. With this approach, developers can focus on building fast and interactive front ends using a JavaScript framework of their choice. Customizing a JavaScript-powered front end is much easier than making changes on a WordPress site.

GraphCMS differs from most Headless CMS platforms in that, instead of delivering content via REST, it does so via GraphQL. This new technology is superior to REST, as it allows us to construct queries that touch on data belonging to multiple models in a single request.

Consider the following model schema:

Post

id: Number title: String content : String comments : array of Comments

Comment

id: Number name: String message: String

The above models have a one(Post)-to-many(Comments) relationship. Let’s see how we can fetch a single Post record attached with all linked Comment records.

If the data is in a relational database, you have to construct either one inefficient SLQ statement, or two SQL statements for fetching the data cleanly. If the data is stored in a NoSQL database, you can use a modern ORM like Vuex ORM to fetch the data easily for you, like this:

const post = Post.query() .with('comments') .find(1);

Quite simple! You can easily pass this data via REST to the intended client. But here’s the problem: whenever the data requirement changes at the client end, you’ll be forced to go back to your back-end code to either update your existing API endpoint, or create a new one that provides the required data set. This back and forth process is tiring and repetitive.

What if, at the client level, you could just ask for the data you need and the back end will provide it for you, without you doing extra work? Well, that’s what GraphQL is for.

Prerequisites

Before we begin, I’d like to note that this is a guide for intermediate to advanced users. I won’t be going over the basics, but rather will show you how to quickly build a Vue.js blog using GraphCMS as the back end. You’ll need to be proficient in the following areas:

ES6 and ES7 JavaScript Vue.js (using CLI version 3) GraphQL

That’s all you need to know to get started with this tutorial. Also, a background in using REST will be great, as I’ll be referencing this a lot. If you’d like a refresher, this article might help: “REST 2.0 Is Here and Its Name Is GraphQL”.

About the Project

We’ll build a very simple blog application with a basic comment system. Below are the links you can visit to check out the completed project:

CodeSandbox.io demo GitHub repo

Please note that a READ-ONLY token has been used in the demo and consequently the comments system won’t work. You’ll need to supply your OPEN permission token and endpoint as per the instructions in this tutorial for it to work.

Create GraphCMS Project Database

Head over to the GraphCMS website and click the “Start Building for Free” button. You’ll be taken to their signup page.

Signing up to GraphCMS

Sign up using your preferred method. Once you’ve completed the account authentication and verification process, you should be able to access the main dashboard.

The GraphCMS main dashboard

In the above example, I’ve already created a project called “BlogDB”. Go ahead and create a new one, and call it whatever you want. After you’ve entered the name, you can leave the rest of the fields in their defaults. Click Create and you’ll be taken to their project plan.

GraphCMS plans

For the purposes of this tutorial, select the free Developer plan then click Continue. You’ll be taken to the project’s dashboard, which looks something like this:

The GraphCMS project dashboard

Go to the Schema tab. We’re going to create the following models, each with the following fields:

Category

name: Single line text, required, unique

Post

slug: Single line text, required, unique title: Single line text, required, unique content: Multi line text

Comment

name: Single line text, required message: Multi line text, required

Use the Create Model button to create models. On the right side, you should find a hidden panel for Fields, which is activated by clicking the Fields button. Drag the appropriate field type onto the model’s panel. You will be presented with a form to fill in your field’s attributes. Do note at the bottom there’s a pink button labeled Advanced. Clicking it will expand the panel to give you more field attributes you can enable.

Field attributes in the Advanced tab

Next, you’ll need to add the relationship between models as follows:

Post > Categories (many-to-many) Post > Comments (one-to-many)

Use the Reference field to define this relationship. You can add this field to any side; GraphCMS will automatically create the opposite relation field in the referenced model. When you’ve completed defining the models, you should have something like this:

GraphCMS models

You’ve now completed the first part. Let’s now provide some data to our models.

GraphQL Data Migration

To add content to your models, you can simply click the Content tab in the project dashboard where you can create new records for each of your models. However, if you find this to be a slow method, you’ll be happy to know that I’ve created a GraphCMS migration tool that copies data from CSV files and uploads them to your GraphCMS database. You can find the project here in this GitHub repository. To start using the project, simply download it into your workspace like this:

git clone git@github.com:sitepoint-editors/graphcsms-data-migration.git cd graphcsms-data-migration npm install

Next, you’ll need to grab your GraphCMS project’s API endpoint and token from the dashboard’s Settings page. You’ll need to create a new token. For the permission level, use OPEN, as this will allow the tool to perform READ and WRITE operations on your GraphCMS database. Create a file called .env and put it at the root of the project:

ENDPOINT=<Put api endpoint here> TOKEN=<Put token with OPEN permission here>

Next, you may need to populate the CSV files in the data folder with your own. Here’s some sample data that has been used:

// Categories.csv name Featured Food Fashion Beauty // Posts.csv title,slug,content,categories Food Post 1,food-post-1,Breeze through Thanksgiving by making this Instant Pot orange cranberry sauce,Food|Featured Food Post 2,food-post-2,This is my second food post,Food Food Post 3,food-post-3,This is my last and final food post,Food Fashion Post 1,fashion-post-1,This is truly my very first fashion post,Fashion|Featured Fashion Post 2,fashion-post-2,This is my second fashion post,Fashion Fashion Post 3,fashion-post-3,This is my last and final fashion post,Fashion Beauty Post 1,Beauty-post-1,This is truly my very first Beauty post,Beauty|Featured Beauty Post 2,Beauty-post-2,This is my second beauty post,Beauty

You can change the content if you want. Make sure not to touch the top row, as otherwise you’ll change the field names. Please note, for the column categories, I’ve used the pipe | character as a delimiter.

To upload the CSV data to your GraphCMS database, execute the following commands in this order:

npm run categories npm run posts

Each script will print out records that have uploaded successfully. The reason we uploaded categories first is so that the posts records can link successfully to existing category records.

If you want to clean out your database, you can run the following command:

npm run reset

This script will delete all your model’s contents. You’ll get a report indicating how many records were deleted for each model.

I hope you find the tool handy. Go back to the dashboard to confirm that data for the Posts and Categories have successfully been uploaded.

With the back end taken care of, let’s start building our front-end blog interface.

Building the Blog’s Front End Using Vue.js

As mentioned earlier, we are going to build a very simple blog application powered by a GraphCMS database back end. Launch a terminal and navigate to your workspace.

If you haven’t got Vue CLI installed, do that now:

npm install -g @vue/cli

Then create a new project:

vue create vue-graphcms

Choose to manually select features, then select the following options:

Features: Babel, Router Router History Mode: Y ESLint with error prevention only Lint on save Config file placement: Dedicated Config Files Save preset: your choice

Once the project creation process is complete, change into the project directory and install the following dependencies:

npm install bootstrap-vue axios

To set up Bootstrap-Vue in our project, simply open src/main.js and add the following code:

import BootstrapVue from "bootstrap-vue"; import "bootstrap/dist/css/bootstrap.css"; import "bootstrap-vue/dist/bootstrap-vue.css"; Vue.config.productionTip = false; Vue.use(BootstrapVue);

Next, we need to start laying down our project structure. In the src/components folder, delete the existing files and create these new ones:

CommentForm.vue CommentList.vue Post.vue PostList.vue

In the src/views folder, delete About.vue and create a new file called PostView.vue. As seen from the demo, we’ll have several category pages each displaying a list of posts filtered by category. Technically, there will only be one page that will display a different list of posts based on an active route name. The PostList component will filter posts based on the current route.

Let’s first set up the routes. Open src/router.js and replace the existing code with this:

import Vue from "vue"; import Router from "vue-router"; import Home from "./views/Home.vue"; import Post from "./views/PostView.vue"; Vue.use(Router); export default new Router({ mode: "history", base: process.env.BASE_URL, linkActiveClass: "active", routes: [ { path: "/", name: "Featured", component: Home }, { path: "/food", name: "Food", component: Home }, { path: "/fashion", name: "Fashion", component: Home }, { path: "/beauty", name: "Beauty", component: Home }, { path: "/post/:slug", name: "Post", component: Post } ] });

Now that we have our routes, let’s set up our navigation menu. Open src/App.vue and replace the existing code with this:

<template> <div id="app"> <b-navbar toggleable="md" type="dark" variant="info"> <b-navbar-toggle target="nav_collapse"></b-navbar-toggle> <b-navbar-brand href="#">GraphCMS Vue</b-navbar-brand> <b-collapse is-nav id="nav_collapse"> <b-navbar-nav> <router-link class="nav-link" to="/" exact>Home</router-link> <router-link class="nav-link" to="/food">Food</router-link> <router-link class="nav-link" to="/fashion">Fashion</router-link> <router-link class="nav-link" to="/beauty">Beauty</router-link> </b-navbar-nav> </b-collapse> </b-navbar> <b-container> <router-view/> </b-container> </div> </template>

This will add a nav bar to the top of our site with links to our different categories.

Save the file and update the following files accordingly:

src/views/Home.vue

<template> <div class="home"> <PostList /> </div> </template> <script> import PostList from "@/components/PostList.vue"; export default { name: "home", components: { PostList } }; </script>

src/components/PostList.vue

<template> <section class="post-list"> <h1>{{ category }} Articles</h1> <hr/> <p>Put list of posts here!</p> </section> </template> <script> export default { name: "PostList", data() { return { category: "" }; }, created() { this.category = this.$route.name; }, watch: { $route() { this.category = this.$route.name; } } }; </script>

Notice that, in the PostList component, we’re using a custom watcher to update our category data property, based on our current URL.

Now we’re ready to perform a quick test to confirm the routes are working. Spin up the Vue.js server using the command npm run serve. Open a browser at localhost:8080 and test each navigation link. The category property should output the same value we defined in route name’s attribute.

A page view of our app

The post How to Build a Vue Front End for a Headless CMS appeared first on SitePoint.

4 Signs It’s a Bad Idea to Quit Your Job

Jul 18, 2019

Description:

And what to do when you have to stay.

Edwarden, a developer and StackExchange user, wanted advice.

His boss yelled at him for requesting a promotion in the future. Or more specifically, asking for advice on the best process for receiving a promotion. Edwarden exceeded his manager's expectations. Other managers were also very happy with his performance as well.

His manager also knew what Edwarden wanted to discuss ahead of time.

It didn't matter.

His manager exploded. He began yelling, shouting and stomping his feet. "You've only been here... how many months?! Seven?! And now you're asking for a promotion!" His manager threw a tantrum and continued to interrupt him until he agreed that he had no "additional concerns."

Here's the Advice He Received from Other Users

You should quit your job.

You should look for a new job, I don't think your boss is going to promote you How many red flags do you need to see before you look for a new job? Do yourself a favor and get out This shows you why the turnover rate is high and why you should try to get out as soon as possible

Is it a bad idea for him to quit his job?

How do you know?

It's not something we're taught in school. We graduate, get a job and then we're just supposed to figure this out on our own. While some of us do, many of us don't.

That's the question.

What are the signs that indicate it's a bad idea to quit your job? First, let's take a look at some of the more common/obvious answers.

The post 4 Signs It’s a Bad Idea to Quit Your Job appeared first on SitePoint.

JavaScript Remains the Queen of Programming Languages

Jul 18, 2019

Description:

This article was originally published on Developer Economics. Thank you for supporting the partners who make SitePoint possible.

Take the Developer Economics survey and have your say on what the next programming language Queen should be. You could win amazing prizes and gear. Discover more.

Welcome to another update on programming language communities. The choice of programming language matters deeply to developers because they want to keep their skills up to date and marketable. Languages are a beloved subject of debate and the kernels of some of the strongest developer communities. They matter to toolmakers too, as they want to make sure they provide the most useful SDΚs.

Language growth

It can be hard to assess how widely used a programming language is. The indices available from players like Tiobe, Redmonk, Stack Overflow’s yearly survey, or Github’s Octoverse are great, but mostly offer only relative comparisons between languages, providing no sense of the absolute size of each community. They may also be biased geographically, or skewed towards certain fields of software development, or open source developers.

The estimates we present here look at active software developers using each programming language, across the globe and across all kinds of programmers. They are based on two pieces of data. First, our independent estimate of the global number of software developers, which we published for the first time in 2017. Second, our large-scale, low-bias surveys which reach more than 20,000 developers every six months. In the survey, we consistently ask developers about their use of programming languages across nine areas of development1, giving us rich and reliable information about who uses each language and in which context.

JavaScript is and remains the queen of programming languages. Its community of 11.7M developers is the largest of all languages. In 2018, 2.5M developers joined the community: the highest growth in absolute numbers and more than the entire population of Swift, Ruby, or Kotlin developers, amongst others. New developers see it as an attractive entry-level language, but also existing developers are adding it to their skillset. Even in software sectors where Javascript is least popular like machine learning or on-device code in IoT, over a quarter of developers use it for their projects.

Python has reached 8.2M active developers and has now surpassed Java in terms of popularity. It is the second-fastest growing language community in absolute terms with 2.2M net new Python developers in 2018. The rise of machine learning is a clear factor in its popularity. A whopping 69% of machine learning developers and data scientists now use Python (compared to 24% of them using R).

Java (7.6M active developers), C# (6.7M), and C/C++ (6.3M) are fairly close together in terms of community size and are certainly well-established languages. However, all three are now growing at a slower rate than the general developer population. While they are not exactly stagnating, they are no longer the first languages that (new) developers look to.

Java is very popular in the mobile ecosystem and its offshoots (Android), but not for IoT devices. C# is a core part of the Microsoft ecosystem. Throughout our research, we see a consistent correlation between the use of C# and the use of Microsoft developer products. It’s no surprise to see desktop and AR/VR (Hololens) as areas where C# is popular. C/C++ is a core language family for game engines and in IoT, where performance and low-level access matter (AR/VR exists on the boundary between games and IoT).

PHP is now the second most popular language for web development and the fifth most popular language overall, with 5.9M developers. Like Python, it’s growing significantly faster than the overall developer population, having added 32% more developers to its ranks in 2018. Despite having (arguably) a somewhat bad reputation, the fact that PHP is easy to learn and widely deployed still propels it forward as a major language for the modern Internet.

The fastest growing language community in percentage terms is Kotlin. It grew by 58% in 2018 from 1.1M to 1.7M developers. Since Google has made Kotlin a first-class language for Android development, we can expect this growth to continue, in a similar way to how Swift overtook Objective-C for iOS development.

Other niche languages don’t seem to be adding many developers, if any. Swift and Objective-C are important languages to the Apple community, but are stable in terms of the number of developers that use them. Ruby and Lua are not growing their communities quickly either.

Older and more popular programming languages have vocal critics, while new, exciting languages often have enthusiastic supporters. This data would suggest that it’s not easy for new languages to grow beyond their niche and become the next big thing. What does this mean for the future of these languages and others like Go or Scala? We will certainly keep tracking this evolution and plan to keep you informed.

The Developer Economics survey is now live.

Have your say on which should be the next programming language Queen and you may win amazing prizes and gear. Discover more.

The post JavaScript Remains the Queen of Programming Languages appeared first on SitePoint.

5 Top WordPress Tools and Services for You to Use in 2019

Jul 17, 2019

Description:

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

If you're looking for the best WordPress tools and services to take your business to the next level this year, you have plenty to choose from – 54,991 WordPress plugins and services, to be exact.

That sounds like really good news until it's time to find the right match for your website-building projects. You need a game plan that defines the plugins you want that will enable your site to attract visitors.

You'll also need a game plan for conducting what could turn out to be a very lengthy and tedious search.

You can save yourself a lot of time and trouble by checking out the must-have WordPress tools and services listed below — one or more of which might be all you'll need.

1. Elementor

Elementor, with its quick and powerful drag-and-drop editor, enables you to create WordPress landing pages and sites without any need for coding. This and several of its other features combine to make Elementor the most advanced WordPress page builder on the market today.

Elementor works with any theme, and in doing so makes it possible to avoid many of the constraints and limitations some themes can impose on web designers. Elementor also works with any WordPress plugin without slowing down your site, and this tool's squeaky clean code also contributes to your site's overall performance.

You can build your site from scratch on Elementor using its large selection of widgets, or you can select among hundreds of pre-designed templates that can be inserted into any page to get off to a quick start or speed up your workflow.

If you were limited to one choice among this list, you might get the most bang for your buck by choosing Elementor. Fortunately, you're not limited, so feel free to select any or all of the remaining 5 tools and services as well.

2. Brizy WordPress Website Builder

The Brizy WordPress website builder is yet another tool that could be the solution to most, and perhaps all, of your design problems. This drag-and-drop website builder is delightfully easy to use, no coding or coding skill is needed, and you can start using it without paying a dime.

Need to have a website up-and-running quickly? Brizy's 240 design blocks, 150 layouts, and 16 popups will take you a long way, particularly if you find starting a website from scratch is a little intimidating.

As for the more detailed aspects of your website design, the Brizy package includes 4,000 free icons, a pop-up builder if you want to create a unique pop-up design, and easily changed fonts and color schemes.

Yet another cool feature is the ease with which you can control how your website will appear on tablets and mobile devices.

3. WordPress Site Care

Creating a website on WordPress can be accomplished easily and efficiently if you have the right tools on hand. Once a website is up and running you can usually maintain it without too much difficulty. That's not always the case, however, especially if you're responsible for keeping multiple websites up to date and in running order.

Let Newt Labs take care of managing and maintaining your WordPress websites, so you can spend your time doing what you enjoy doing best – building one high-performing, client-satisfying website after another.

The Newt Labs team can help you with small fixes, managing WordPress updates, providing backups, WordPress optimized cloud hosting, and more.

The WordPress site care they can provide will not only make your work life a little easier, but it will protect your reputation as well by addressing potential problems before they become real.

4. Goodie

The Goodie platform joins end-clients directly with a developer, allowing them to avoid go-betweens that can sometimes be costly, time-consuming, or a communications bottleneck when attempting to accurately transform a design into code. Goodie can completely code your website at a special price of $999.

The only thing Goodie needs from you is your design – a great solution for small businesses in need of a carefully coded website.

5. Wordlift

WordLift is the first WordPress plugin to use artificial intelligence for SEO. It grows your website's organic traffic by creating machine-friendly content that chatbots, search crawlers, and personal digital assistants like Google Assistant, Siri and Alexa use to help consumers take actions.

WordLift adds a layer of metadata and builds a knowledge graph Google uses to match the searcher's intent. Moreover, it measures content performance in terms of traffic per topic and in this way it helps editors improve their editorial plan and increase their reach.

Tips to Make Your WordPress Site Secure Choose a good hosting company

Don't be tempted to go with a cheap hosting provider. Going with one that provides multiple layers of security could save you lost or redirected data nightmares down the road.

Install a WordPress security plugin

Installing a WordPress security plug that monitors your site 24/7 and checks for site security issues is far easier than doing a periodic site security check on your own, especially if you lack development skills.

Update WordPress regularly

Whenever WordPress is updated improvements are made, bugs are eliminated, and security is improved. If you don't update regularly, some of those bugs could bite you. To update WordPress, go to the dashboard and check to see if a new version has been released. If so, click to update and click the Update Now button.

Back up your site regularly

It's all about creating a copy of all your site's data and storing it in a safe place. By doing so, you'll be able to restore the site from your backup copy should anything bad happen.

Conclusion

9 items of value – 5 top tools and services and 4 operation and maintenance tips. Pick one or more of the tools and services and follow through with the tips as you complete your site, and you should be in great shape.

High-performance websites you can build yourself (or with the help of a developer), and a solid security and maintenance program should combine to make your life a lot easier.

The post 5 Top WordPress Tools and Services for You to Use in 2019 appeared first on SitePoint.

The Tao of Digital Agency Profitability

Jul 16, 2019

Description:

a Taoish feature image

It’s 2019, and despite years of people espousing the death of the “digital agency”, the industry is thriving and confident. Amazing work continues to be produced by top digital agencies around the world, and clients continue to hire agencies to complement their internal teams, in particular when creative or technical innovation is required.

a Taoish feature image

And not only that, well managed digital agencies are producing world class work whilst also achieving strong profit margins. Yes, it is possible to balance the creative Yin with the operational Yang. But it requires focus and discipline. And maybe a little luck.

Our objective for this article is to distill and understand the main drivers of agency profitability, and provide tips, tactics and techniques that agency leaders can put into practice in their own businesses.

To do this, we asked the leaders of ten digital agencies from the SoDA membership for their secrets of success in the pursuit of healthy profit margins — what has worked for them, what hasn’t, and for any surprising insights and ideas they can share.

SoDA is a member-based network of 100 of the best digital agencies in the world, many of whom are globally renowned for their creative and technical innovation. Lesser known is the amazing talent in the management, finance, operations and sales teams of these agencies, who work in support of their creative endeavors.

The agency leaders we interviewed have run or are still running some of the best digital agencies on the planet. Half of those interviewed have had their digital agency be acquired, whilst the other half continue to work in and grow as independent agencies. Some run global agencies with offices around the world, others are based in one location.

A common thread with the agencies we interviewed is not just the financial discipline, but the quality of the work — with awards including the Emmys, Cannes Lions, the Webby Awards, One Show and pretty much anything else you can imagine. Financial performance and quality work are not mutually exclusive!

After we received the interview responses, we compared these against the SoDA 2018 KPI Benchmark Study, a detailed annual survey that saw 61 digital agencies provide data against hundreds of key metrics. We isolated the data for global averages and top performers and used this to provide benchmark figures, which are highlighted in grey throughout the article. The global average for EBITDA performance was around 10% while top performers delivered margins of 20% or more.

The result of the interviews and qualitative research are eight Key Drivers that we believe drive superior agency profitability:

nurture repeat customers reduce project cost overruns maximize billable utilization have keen financial discipline build a strong sales pipeline develop a capability for low cost delivery manage your ratio of billable vs non-billable staff value your people and culture

Each section below includes a description of how that Key Driver impacts profitability, how to measure the impact, and ideas for improving performance in this area.

Acknowledging that there are many flavors of digital agency, we hope that the ideas below will create some awareness of how profit can be maximized, and spark inspiration and action.

Let’s get started!

Nurture Repeat Customers

If you want to improve profitability in your agency and have time to do only one thing, do this. Almost all of the agencies who collaborated on this article recommend increasing the amount of repeat business you get vs pitching for work with new clients.

Long-term client relationships results in higher profit for the agency than individual projects, in part due to the trust that builds with the client (allowing your agency to charge appropriately for your services), and also for the reduced new business costs of pitching. Win rates when bidding for work with an existing client are typically twice as high as with new potential clients, and so the cost of pitching and losing is drastically reduced.

As Bill Fritsch, former Chariman and CEO of Digital Kitchen says:

Serious profitability comes when clients value your work and feel valued by your team. When they prefer working with your organization versus other firms, clients are more willing to work in partnership and to pay more for your service.

A good benchmark is to have over 70% of your annual revenue from existing clients (i.e. clients that were already a client last year) and the remainder from new clients you have won throughout the year.

There are both “hunting” and “farming” components to growing repeat business:

Hunting: when your agency is invited to pitch for a new piece of work, in addition to your other qualification questions ask yourself whether this is a project or an account that you are bidding for. Ideally if your pipeline is strong enough you can turn down opportunities that are project-based, and concentrate your energy on those that could have long-term potential.

Advice from Russ Whitman (founder of Ratio, acquired in 2017 and now Managing Director at Globant is that when bidding for new work, change the conversation from talking about “projects” to “partnership”. Once you have won the project, Russ says “your #1 goal is to sell the long-term rolling program”.

Image of green mountains

Arming: keeping and growing a client account requires excellence in project delivery, and so the Project Manager becomes a key role in the business. Some agencies have a compensation plan to incentivize Project Managers based on profitable project delivery as well as growth of revenue with their clients.

Naturally, the PM needs to be surrounded by the right team to guarantee quality delivery. UK digital agency Red Badger take this very seriously, and as Cain Ullah (founder and CEO) says, they —

will only take on a new project if we can resource it with a high quality team with the appropriate blend of experience and resources that have worked on previous Red Badger projects.

Swift resolution of issues is also important. At one of Bill Fritsch’s agencies —

we created a special FIRE ALERT line. If clients had hot issues, this line would be answered 24/7. And whoever was on the Fire line was rewarded for getting answers so clients didn’t have to sweat.

If you are delivering projects well, and managing issues swiftly, you should hopefully have earned permission to ask for more work from that client. As Bill suggests:

encouraging clients to do more with your firm can be as simple as training people to “always have an idea” that leads to the next thing. We developed a reward system that gave significant bonuses to client teams that turned the first project into a second opportunity before the first project was delivered. And an even bigger bonus for winning a third assignment in the same period of time.

A critical aspect of increasing client loyalty, longevity and revenue is to keep in touch with how happy they are with your agency. A client survey on a regular basis can help to benchmark client satisfaction and keep people in the agency focused on continuous improvement. The most common method is using an NPS score to track client satisfaction, along with a number of qualitative questions you could include in a (short) client survey.

This doesn’t replace regular face-to-face discussions with the client of course, whether in a formal or social setting — and this is also something you can set a goal against and measure — all of your most important client accounts should see you personally at least once every few months.

The post The Tao of Digital Agency Profitability appeared first on SitePoint.

Getting Started with October CMS Static Pages

Jul 15, 2019

Description:

These days it can be tough for website developers, especially now with WordPress going through the biggest and the most dramatic update in its history. Over the past few months, we’ve observed a growing interest in the October CMS community.

October CMS is the natural choice for developers that look for a modern and reliable content management system based on the Laravel PHP framework. Launched in 2014, today October CMS is a mature platform with a large ecosystem. October CMS is known for its reliability and non-breaking updates, which is greatly appreciated by developers and their clients. The philosophy “Getting back to basics” really matters to freelancers and digital studios, whose businesses depend on the quality of the software they use. The quickly growing Marketplace and the supporting businesses built around October are great proof of the community’s trust. In 2018 October CMS was also voted the Best Flat File CMS in the CMS Critic Award contest.

October CMS has a simple extensible core. The core provides basic CMS functions and a lot of functionality can be added with plugins from the Marketplace. The plugins Marketplace includes a lot of product categories, which include blogging, e-commerce, contact forms, and many others.

In this tutorial, we will demonstrate how to create a website with pages editable in WYSIWYG (What You See Is What You Get) mode, and blogging features. We will use the Static Pages plugin that allows you to create a dynamic website structure with pages and menus manageable by non-technical end users. At the same time, the website will include dynamic blog pages, with content managed with the Blog plugin. All plugins used in this tutorial are free for anyone to install. The ideas from this tutorial can be extended to creating more complex websites. Themes implementing similar features can be found on the Themes Marketplace, but the goal of this tutorial is to show how easy it is to make an October website from scratch.

This is what we will have at the end:

The website theme is completely based on Twitter Bootstrap 4.3. The demo website also includes a simple CSS file that manages some light styling features, such as padding and colors, but since it is not relevant for the topic of this tutorial, it won’t be described in this guide.

Installing October CMS

To install October CMS you must have a web server meeting the minimum requirements. You can use MAMP as a solution to try October on your computer.

The post Getting Started with October CMS Static Pages appeared first on SitePoint.

8 of the Best Design Handoff Tools

Jul 11, 2019

Description:

A Roundup of the Best Design Handoff Tools

Design handoff (before it was even called that) was a complicated, frustrating, and often disastrous task. Way back when, Photoshop was the only tool available for screen design, and converting a design to code was called “slicing a PSD.”

Oh, the days.

Slicing a PSD was the developer’s responsibility, which was quite frustrating because developers understandably didn’t want to work with design tools. That being said, designers had to manually write out design specs for every layer in a Photoshop document, which often resulted in inconsistencies and heated discussions with developers. This set designers and developers on a path of war that even today we’re not ready to joke about.

But eventually we were introduced to Sketch. Thanks to its extensible API, developers were able to build apps that could analyze and interpret design documents completely. Today, design handoff tools have become a must-have in every design workflow, with almost every screen design tool integrating with (or providing its own) design handoff solution.

What Do Design Handoff Tools Do?

Design handoff tools have three main objectives:

to help designers export their designs from [insert tool here] to help developers inspect and implement said design to facilitate feedback and collaboration between stakeholders

The design handoff workflow often looks like this:

The designer mocks up the design in a screen design tool. The designer sends the mockups to a design handoff tool. Stakeholders look at the design, and make comments if needed. The designer fixes any issues, then sends an updated version. The developer then inspects the finished design, layer-by-layer. Design handoff tools translate each layer into code, and the developer can then use this code as the basis for developing the app or website.

Without design handoff, developers are left with only one alternative: guessing. Guessing can result in inaccuracies — for example the wrong colors being used, or an interaction behaving incorrectly — which in turn impacts user experience.

All handoff tools work the same way, but they don’t all support the same platforms or your screen design tool of choice. If you don’t use Sketch, for example, Marvel isn’t going to be all that useful to you as a design handoff tool.

Let’s take a look at the best design handoff tools that are currently available.

Zeplin

Zeplin has been leading the charge on design handoff since the concept was first realized, integrating with Sketch and Photoshop, and more recently Adobe XD and Figma. Designs synced from any of these tools can be translated into CSS, Android, Swift, Objective-C or React Native code, which includes the styles of each layer and any assets that have been marked as exportable.

The Zeplin dashboard

This functionality is standard for design handoff tools, although with Zeplin being the first (or at least one of the first), the user experience of their app is almost unrivaled.

And as with all other design handoff tools, commenting features are there to aid feedback and collaboration.

Platforms: Web, macOS, Windows Pricing: Free Plan, $17, $26, or $122.40 (/month)

The post 8 of the Best Design Handoff Tools appeared first on SitePoint.

How to Plot Charts in Python with Matplotlib

Jul 10, 2019

Description:

You generate a huge amount of data on a daily basis. A critical part of data analysis is visualization. A variety of graphing tools have developed over the past few years. Given the popularity of Python as a language for data analysis, this tutorial focuses on creating graphs using a popular Python library — Matplotlib.

Matplotlib is a huge library, which can be a bit overwhelming for a beginner — even if one is fairly comfortable with Python. While it is easy to generate a plot using a few lines of code, it may be difficult to comprehend what actually goes on in the back-end of this library. This tutorial explains the core concepts of Matplotlib so that one can explore its full potential.

Let's get started!

Prerequisites

The library that we will use in this tutorial to create graphs is Python's matplotlib. This post assumes you are using version 3.0.3. To install it, run the following pip command in the terminal.

pip install matplotlib==3.0.3

To verify the version of the library that you have installed, run the following commands in the Python interpreter.

>>> import matplotlib >>> print(matplotlib.__version__) '3.0.3'

If you are using Jupyter notebooks, you can display Matplotlib graphs inline using the following magic command.

%matplotlib inline Pyplot and Pylab: A Note

During the initial phases of its development, Mathworks' MATLAB influenced John Hunter, the creator of Matplotlib. There is one key difference between the use of commands in MATLAB and Python. In MATLAB, all functions are available at the top level. Essentially, if you imported everthing from matplotlib.pylab, functions such as plot() would be available to use.

This feature was convenient for those who were accustomed to MATLAB. In Python, though, this could potentially create a conflict with other functions.

Therefore, it is a good practice to use the pyplot source.

from matplotlib import pyplot as plt

All functions such as plot() are available within pyplot. You can use the same plot() function using plt.plot() after the import earlier.

Dissecting a Matplotlib Plot

The Matplotlib documentation describes the anatomy of a plot, which is essential in building an understanding of various features of the library.


Source

The major parts of a Matplotlib plot are as follows:

Figure: The container of the full plot and its parts Title: The title of the plot Axes: The X and Y axis (some plots may have a third axis too!) Legend: Contains the labels of each plot

Each element of a plot can be manipulated in Matplotlib's, as we will see later.

Without further delay, let's create our first plot!

Create a Plot

Creating a plot is not a difficult task. First, import the pyplot module. Although there is no convention, it is generally imported as a shorter form &mdash plt. Use the .plot() method and provide a list of numbers to create a plot. Then, use the .show() method to display the plot.

from matplotlib import pyplot as plt plt.plot([0,1,2,3,4]) plt.show()

Your first plot with matplotlib

Notice that Matplotlib creates a line plot by default. The numbers provided to the .plot() method are interpreted as the y-values to create the plot. Here is the documentation of the .plot() method for you to further explore.

Now that you have successfully created your first plot, let us explore various ways to customize your plots in Matplotlib.

Customize Plot

Let us discuss the most popular customizations in your Matplotlib plot. Each of the options discussed here are methods of pyplot that you can invoke to set the parameters.

The post How to Plot Charts in Python with Matplotlib appeared first on SitePoint.

Learn to Design and Animate in 3D with Zdog

Jul 9, 2019

Description:

There's a cool JavaScript library that names like Chris Gannon, Val Head, and CodePen are all raving about. You can also find it on ProductHunt, where it's been doing rather well. The library is none other than Dave DeSandro's Zdog.

In this article, I'm going to introduce you to Zdog and show you some cute demos made by amazing devs that you can reverse-engineer and learn from.

Let's dive in!

What Is Zdog

DeSandro explains what Zdog is about on the library's dedicated website:

The post Learn to Design and Animate in 3D with Zdog appeared first on SitePoint.

How to Use Git Branches & Buddy to Organize Project Code

Jul 9, 2019

Description:

This article was created in partnership with Buddy. Thank you for supporting the partners who make SitePoint possible.

In this article, you will learn how to set up continuous integration/deployment pipelines for your branching workflow. We will be using Buddy CI/CD services to set up the pipelines. We'll use a basic JavaScript project where we'll set up a couple of development branches. I'll show you how to automate testing on each type of branch. I'll also be introducing the concept of branching workflows, and show a few examples you can adopt in your projects.

Prerequisites

To follow along with this tutorial, you only need basic Node.js skills. You also need to be conversant with Git. Here are a couple of articles to help you out:

Git for Beginners Git for Teams Our book, Jump Start Git

In order to set up our pipelines, we will need to write a few tests using Jest. You don't need to learn Jest if you are new to it — the focus for this article is to learn how to set up pipelines that will automatically pick new branches and build them for you. Before we get to that, we should look into various branch strategies we can use.

Zero Branch Strategy

01-basic-git-workflow

The Zero Branch Strategy is simply a fancy way of saying "you are not using any branch strategy." It's also known as a basic workflow. You only have a master branch where you directly commit and build your releases. This strategy is convenient and good if the project is:

Small and simple Hardly requires updates Managed by a solo developer

Such projects include tutorials, demos, prototypes, starter project templates and personal projects. However, there are several cons to this approach:

Multiple merge conflicts will likely occur if more than one person is working on the project You won't be able to develop multiple features and fix issues concurrently Removing and restoring features will be a difficult task Your team will spend too much time dealing with version control issues instead of working on new features

All these issues can be resolved by adopting a branch strategy. This should give you:

Ability to work independently and push changes to the shared repository without affecting your team members Ability to merge your teammates' code with your changes and quickly resolve any conflicts that may come up Assurance that code standards are maintained and collaboration efforts run smoothly regardless of the size of your team

Do note that there are many types of branch workflows you are free to pick. You can also create your own custom branch workflow that works best for you. Let's start with the simplest branch strategy.

Develop Branch Strategy

02-develop-branch-workflow

In this strategy, you set up a long-living branch called develop that runs alongside the master branch. All work is committed first to the develop branch. This is a safe place where you can introduce new code that might break your project. You'll need a testing strategy in place in order to ensure that you don't introduce bugs to the master branch when you merge the changes.

The pros of this workflow are:

The post How to Use Git Branches & Buddy to Organize Project Code appeared first on SitePoint.

Is the Rise of Millennial Women in Tech Just an Illusion?

Jul 8, 2019

Description:

woman with computer

This article was created in partnership with the Developer Economics Survey. Thank you for supporting the partners who make SitePoint possible.

The latest Developer Economics survey is upon us again, and as always, we highly recommend that everyone participates. It’s an excellent opportunity to express your views about what’s happening in the world of web development, and it helps paint a cohesive picture about the landscape.

In the last survey, published April 2019, we garnered a lot of interesting insights into the modern dev at work. Of the participants in the last survey, 9% were women, suggesting a global population of 1.7 million women developers versus the 17 million that are men. However, the report also found that under the age of 35, 36% of developers were women, versus 33% of men. Compare this with the survey’s other finding that 37% of male developers are over 35 years of age, as compared to 29% of women in the same age bracket. This indicates that younger generations of women are increasingly moving towards a career in development. Hopefully in the next few years we’ll start seeing parity between male and female developers in more senior roles. Currently men are almost three times more likely to hold senior or C-suite positions than women.

However, as the report also notes, a less optimistic reading of the data may be that women “have always been involved, but tend to leave software development as they get older, either by choice or necessity.”

The post Is the Rise of Millennial Women in Tech Just an Illusion? appeared first on SitePoint.

SitePoint Premium New Releases: Modern JavaScript, Kanban + DevTools

Jul 5, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

The Versioning Guide to Modern JavaScript

A guided tour of the breadth of modern JavaScript, including frameworks, state management, GraphQL, Node, Electron, design patterns, tools, testing and a lot more.

➤ Read The Versioning Guide to Modern JavaScript.

Browser Devtool Secrets

Browser development tools have evolved from basic consoles to fully integrated development environments. It’s become possible to alter and inspect any aspect of your web application, but few of us venture beyond the basics. In this guide, we’ll explore the features you may not have considered.

➤ Read Browser Devtool Secrets.

Practical Kanban

This book will give you practical answers to these questions: Are we using Kanban properly? How can we improve our Kanban? How can we scale our Kanban? How can our work become more predictable? How can we prioritize?

➤ Read Practical Kanban.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Modern JavaScript, Kanban + DevTools appeared first on SitePoint.

A Beginner’s Guide to Working With Components in Vue

Jul 5, 2019

Description:

A Beginner’s Guide to Working With Components in Vue

One of the great things about working with Vue is its component-based approach to building user interfaces. This allows you to break your application into smaller, reusable pieces (components) which you can then use to build out a more complicated structure.

In this guide, I’ll offer you a high-level introduction to working with components in Vue. I’ll look at how to create components, how to pass data between components (via both props and an event bus) and how to use Vue’s <slot> element to render additional content within a component.

Each example will be accompanied by a runnable CodePen demo.

How to Create Components in Vue

Components are essentially reusable Vue instances with a name. There are various ways to create components within a Vue application. For example, in a small- to medium-sized project you can use the Vue.component method to register a global component, like so:

Vue.component('my-counter', { data() { return { count: 0 } }, template: `<div>{{ count }}</div>` }) new Vue({ el: '#app' })

The name of the component is my-counter. It can be used like so:

<div id="app"> <my-counter></my-counter> </div>

When naming your component, you can choose kebab case (my-custom-component) or Pascal case (MyCustomComponent). You can use either variation when referencing your component from within a template, but when referencing it directly in the DOM (as in the example above), only the kebab case tag name is valid.

You might also notice that, in the example above, data is a function which returns an object literal (as opposed to being an object literal itself). This is so that each instance of the component receives its own data object and doesn’t have to share one global instance with all other instances.

There are several ways to define a component template. Above we are using a template literal, but we could also use a <script tag> marked with text/x-template or an in-DOM template. You can read more about the different ways of defining templates here.

Single-file Components

In more complex projects, global components can quickly become unwieldy. In such cases, it makes sense to craft your application to use single-file components. As the name suggests, these are single files with a .vue extension, which contain a <template>, <script> and <style> section.

For our example above, an App component might look like this:

<template> <div id="app"> <my-counter></my-counter> </div> </template> <script> import myCounter from './components/myCounter.vue' export default { name: 'app', components: { myCounter } } </script> <style></style>

And a MyCounter component might look like this:

<template> <div>{{ count }}</div> </template> <script> export default { name: 'my-counter', data() { return { count: 0 } } } </script> <style></style>

As you can see, when using single-file components, it’s possible to import and use these directly within the components where they’re needed.

In this guide, I’ll present all of the examples using the Vue.component() method of registering a component.

Using single-file components generally involves a build step (for example, with Vue CLI). If this is something you’d like to find out more about, please check out “A Beginner’s Guide to Vue CLI” in this Vue series.

Passing Data to Components Via Props

Props enable us to pass data from a parent component to child component. This makes it possible for our components to be in smaller chunks to handle specific functionalities. For example, if we have a blog component we might want to display information such as the author’s details, post details (title, body and images) and comments.

We can break these into child components, so that each component handles specific data, making the component tree look like this:

<BlogPost> <AuthorDetails></AuthorDetails> <PostDetails></PostDetails> <Comments></Comments> </BlogPost>

If you’re still not convinced about the benefits of using components, take a moment to realize how useful this kind of composition can be. If you were to revisit this code in the future, it would be immediately obvious how the page is structured and where (that is, in which component) you should look for which functionality. This declarative way of composing an interface also makes it much easier for someone who isn’t familiar with a codebase to dive in and become productive quickly.

Since all the data will be passed from the parent component, it can look like this:

new Vue({ el: '#app', data() { return { author: { name: 'John Doe', email: 'jdoe@example.com' } } } })

In the above component, we have the author details and post information defined. Next, we have to create the child component. Let’s call the child component author-detail. So our HTML template will look like this:

<div id="app"> <author-detail :owner="author"></author-detail> </div>

We’re passing the child component the author object as props with the name owner. It’s important to note the difference here. In the child component, owner is the name of the prop with which we receive the data from the parent component. The data we want to receive is called author, which we’ve defined in our parent component.

To have access to this data, we need to declare the props in the author-detail component:

Vue.component('author-detail', { template: ` <div> <h2>{{ owner.name }}</h2> <p>{{ owner.email }}</p> </div> ´, props: ['owner'] })

We can also enable validation when passing props, to make sure the right data is being passed. This is similar to PropTypes in React. To enable validation in the above example, change our component to look like this:

Vue.component('author-detail', { template: ` <div> <h2>{{ owner.name }}</h2> <p>{{ owner.email }}</p> </div> `, props: { owner: { type: Object, required: true } } })

If we pass the wrong prop type, you’ll see an error in your console that looks like what I have below:

"[Vue warn]: Invalid prop: type check failed for prop 'text'. Expected Boolean, got String. (found in component <>)"

There’s an official guide in the Vue docs that you can use to learn about prop validation.

See the Pen Vue Componets - Props by SitePoint (@SitePoint) on CodePen.

The post A Beginner’s Guide to Working With Components in Vue appeared first on SitePoint.

An Introduction to Cloudflare Workers

Jul 3, 2019

Description:

An Introduction to Cloudflare Workers

Cloud computing in its various incarnations — SaaS, PaaS, IaaS — has had big successes. Some of us still recall the $212 million purchase of PaaS provider Heroku in 2010, which at that time was — architecturally speaking — little more than a high-level deployment layer. It had a very posh gem for smooth and easy deployment of apps and frameworks like RoR, Python or Node apps running on Amazon's infrastructure. The concept of Serverless Computing was born.

There have been a host of different models for cloud products ever since then. Various experiments have come and gone as providers looks for the sweet spot, with proliferation continuing and new terms being born, like BaaS and MBaaS.

Protocol Labs, a crypto startup looking to redefine the cloud model, collected $257 million in its 2017 ICO, breaking all records. Airtable, with its high-level, spreadsheet-meets-database products and api, reached a $1.1 billion valuation in its 2018 financing round.

Serverless Computing

Serverless computing is a subset term of cloud computing that makes a point of doing away with the classical server product, providing developers with a high-level environment to run their code, charged on an as-used basis, and freeing those developers from worrying about the underlying software stack.

Serverless computing has allowed further flexibility in paying for used processing power, rather than paying for pre-allocated packages as with classical cloud.

The term “serverless” is semantically wrong, because the code is still executed on a server, but users conceptually don't have to deal with servers anymore. Provided certain conventions are adhered to, the underlying stack, and all the infrastructure and deployment issues, are handled by vendors.

The main type of product that sprang out from this is FaaS — a cloud execution environment, or a runtime that allows deployment of code without any boilerplate. Amazon's Lambda, Oracle Fn and Alibaba's Function Compute are some examples.

Cloudflare

Cloudflare is a San Francisco company that was started nine years ago. It's a Content Delivery Network that provides delivery of static assets for websites from its global network of edge nodes. It also provides firewall and DDOS protection, and has a reputation for the fastest DNS service on the internet.

When talking about Cloudflare, and what it brings to the arena of serverless computing, it’s necessary to add one more term to the list of cloud buzzwords we used here — edge computing.

As explained on Wikipedia:

The post An Introduction to Cloudflare Workers appeared first on SitePoint.

Top 8 Portfolio WordPress Themes for Creatives in 2019

Jul 2, 2019

Description:

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

Creating a decent portfolio requires covering a lot of bases. Showcasing your work may actually be the easiest part; while ensuring that the text accompanying each piece gives the right level of context can be a challenge. It has to catch people's attention without shifting focus away from the work itself.

There's no shortage of themes you could use to create a decent portfolio website, but if you're not certain as to the functionality you might require, finding a satisfactory one can be difficult. Your search can be even more difficult if your goal is to create a portfolio website that's much more than "decent".

You need a theme that provides a simple way to organize your work, one that's bundled with a good combination of plugins, and one that will enable you to create something awesome you can share with the world.

There are lots of WordPress themes available, including the best-in-class themes in the list we've prepared.

1. Be Theme



Be Theme has all the features, functionalities, and design options web designers will ever need to build high-quality portfolio websites, and any other type of website for that matter. Thanks to its selection of 450+ customizable pre-built websites, its library of 200+ shortcodes plus a shortcode generator, you can create an awesome portfolio website in 4 hours or less with absolutely no need for coding.

The post Top 8 Portfolio WordPress Themes for Creatives in 2019 appeared first on SitePoint.

Talk Tech with Us in Our New Discord Community

Jul 2, 2019

Description:

Want a place to chat about coding, design, the web, and technology at large with likeminded people?

Or perhaps you work remotely and need a community that can travel with you?

SitePoint Discord serverWe're opening our Discord to the public today. We wanted to create a casual place where we could chat about cool tech and getting stuff done, without the exhibitionism and divisive atmosphere of social media, but with that real-time sense of community.

Our server is a baby server, and there's a lot of work to be done, but for now we have rooms for all sorts of conversation. Whether you want to puzzle out web development issues or talk games, we've got you covered.

Sign up to our Discord and start chatting with SitePoint staff, members, and the wider developer community!

It's 100% free. Come on in and have chat with us!

⚡️ Join us for a chat now.

The post Talk Tech with Us in Our New Discord Community appeared first on SitePoint.

The Precarious Nature of Running a Digital Publication in 2019

Jul 2, 2019

Description:

Clickbait is not your friend

This article was created in partnership with Proper Media. Thank you for supporting the partners who make SitePoint possible.

Recently, there have been countless articles and think pieces written about the decline of publishing. These articles often illustrate how difficult it is for publishers to monetize what they do to eke out a sustainable business model.

In reality, advertising revenue is down for independent publishers across the board. More people are using advanced ad blocking software, which is impacting the number of ads publishers can show. Plus there are two giant elephants in the room — Google and Facebook. These two entities combined account for almost 60% of the total advertising spend online. This duopoly uses third-party publisher content to bring in advertising revenue, but leaves very little revenue for the publishers themselves. For better or worse, they also have the scale to very effectively monetise their user base, which a smaller publisher just can’t compete with. Facebook, for example, has an average CPM of around $8 compared to an average CPM of $1 for third-party publishers. As the online advertising world evolves, publishers will face new obstacles to monetize their websites.

[caption id="attachment_172667" align="alignnone" width="470"]Top 5 companies, ranked by US net digital ad revenue share 2018 & 2019 Source: eMarketer[/caption]

To overcome these difficulties, publishers have all tried different ways to generate revenue in this new landscape; the New York Times and many others have tried to sell premium subscriptions to their users by hiding their content behind paywalls. Another example of subscription-based revenue is Apple News+, which is an attempt to distribute some subscription revenue to publishers, albeit after Apple takes its healthy cut. However, consumers are still very unlikely to pay for content online. A study by Reuters Institute and Oxford University recently found that only 13% of people in the US pay for an ongoing news solution.

Paywalls have worked effectively for some publishers like the New York Times, where they have seen year-on-year revenue growth for their premium subscription product. But this is just not feasible for a lot of others, who are seeing a backlash from users to this system. In addition to being ineffective for many publishers, paywalls are inherently at odds with a publisher’s goals. Publishers want to produce content that educates and informs the largest number of people, which is the opposite of how a paywall operates. With these constraints around subscription-based website monetization, traditional display advertising has remained a large part of overall publisher revenue, including ours.

The simple fact is advertising has always been integral to an online publisher like us—it is how we here at SitePoint keep everything running and pay for our writers to produce interesting content that you come to read. We, like all other businesses, have to generate revenue. We’ve faced the same challenges over the years and the same struggle to strike a balance between generating revenue with advertising (in order to continue to produce a plethora of free, educational content), while creating a user experience that allows our readers to digest and enjoy that content without annoyance. We admittedly do not always get this balance right.

Currently, we’re teamed up with Proper Media as our programmatic revenue partner, in hopes of finding that balance. The way it works is that we leverage Proper’s header bidding solution to monetize the ad slots on our article pages. Working with Proper allows us to get the highest CPMs by creating competition for our inventory across all the top advertising demand available (e.g. Amazon’s A9, Google Adx, and AOL’s OATH). Additionally, they take care of the direct demand for ad sales. Gone are the days when advertisers bought large advertising blocks from individual publishers — nowadays, it is all run programmatically.

In short, Proper handles the monetization so we can focus on producing great content. They ensure that our ad revenue is as high as possible. They have continuous data-driven optimization and granular real-time reporting which ensure that we are always getting the best yield for our ad units. They also handle all of the receivables and deliver a consolidated payment that is on faster terms than all major exchanges, which really helps the cash flow of a small publisher like us.

The post The Precarious Nature of Running a Digital Publication in 2019 appeared first on SitePoint.

Build a Real-time Chat App with Pusher and Vue.js

Jul 1, 2019

Description:

Build a Real-time Chat App with Pusher and Vue.js

Apps that communicate in real time are becoming more and more popular nowadays, as they make for a smoother, more natural user experience.

In this tutorial, we’re going to build a real-time chat application using Vue.js powered by ChatKit, a service provided by Pusher. The ChatKit service will provide us with a complete back end necessary for building a chat application on any device, leaving us to focus on building a front-end user interface that connects to the ChatKit service via the ChatKit client package.

Prerequisites

This is an intermediate- to advanced-level tutorial. You’ll need to be familiar with the following concepts to follow along:

Vue.js basics Vuex fundamentals employing a CSS framework

You’ll also need Node installed on your machine. You can do this by downloading the binaries from the official website, or by using a version manager. This is probably the easiest way, as it allows you to manage multiple versions of Node on the same machine.

Finally, you’ll need to install Vue CLI globally with the following command:

npm install -g @vue/cli

At the time of writing, Node 10.14.1 and Vue CLI 3.2.1 are the latest versions.

About the Project

We’re going to build a rudimentary chat application similar to Slack or Discord. The app will do the following:

have multiple channels and rooms list room members and detect presence status detect when other users start typing

As mentioned earlier, we’re just building the front end. The ChatKit service has a back-end interface that will allows us to manage users, permissions and rooms.

You can find the complete code for this project on GitHub.

Setting up a ChatKit Instance

Let’s create our ChatKit instance, which is similar to a server instance if you’re familiar with Discord.

Go to the ChatKit page on Pusher’s website and click the Sign Up button. You’ll be prompted for an email address and password, as well as the option to sign in with GitHub or Google.

Select which option suits you best, then on the next screen fill out some details such as Name, Account type, User role etc.

Click Complete Onboarding and you’ll be taken to the main Pusher dashboard. Here, you should click the ChatKit Product.

The ChatKit dashboard

Click the Create button to create a new ChatKit Instance. I’m going to call mine VueChatTut.

Creating a new ChatKit instance

We’ll be using the free plan for this tutorial. It supports up to 1,000 unique users, which is more than sufficient for our needs. Head over to the Console tab. You’ll need to create a new user to get started. Go ahead and click the Create User button.

Creating a ChatKit user

I’m going to call mine “john” (User Identifier) and “John Wick” (Display Name), but you can name yours however you want. The next part is easy: create the two or more users. For example:

salt, Evelyn Salt hunt, Ethan Hunt

Create three or more rooms and assign users. For example:

General (john, salt, hunt) Weapons (john, salt) Combat (john, hunt)

Here’s a snapshot of what your Console interface should like.

A snapshot of the console

Next, you can go to the Rooms tab and create a message using a selected user for each room. This is for testing purposes. Then go to the Credentials tab and take note of the Instance Locator. We’ll need to activate the Test Token Provider, which is used for generating our HTTP endpoint, and take a note of that, too.

Test token

Our ChatKit back end is now ready. Let’s start building our Vue.js front end.

Scaffolding the Vue.js Project

Open your terminal and create the project as follows:

vue create vue-chatkit

Select Manually select features and answer the questions as shown below.

Questions to be answered

Make doubly sure you’ve selected Babel, Vuex and Vue Router as additional features. Next, create the following folders and files as follows:

Files and folders to create

Make sure to create all the folders and files as demonstrated. Delete any unnecessary files that don’t appear in the above illustration.

For those of you that are at home in the console, here are the commands to do all that:

mkdir src/assets/css mkdir src/store touch src/assets/css/{loading.css,loading-btn.css} touch src/components/{ChatNavBar.vue,LoginForm.vue,MessageForm.vue,MessageList.vue,RoomList.vue,UserList.vue} touch src/store/{actions.js,index.js,mutations.js} touch src/views/{ChatDashboard.vue,Login.vue} touch src/chatkit.js rm src/components/HelloWorld.vue rm src/views/{About.vue,Home.vue} rm src/store.js

When you’re finished, the contents of the src folder should look like so:

. ├── App.vue ├── assets │ ├── css │ │ ├── loading-btn.css │ │ └── loading.css │ └── logo.png ├── chatkit.js ├── components │ ├── ChatNavBar.vue │ ├── LoginForm.vue │ ├── MessageForm.vue │ ├── MessageList.vue │ ├── RoomList.vue │ └── UserList.vue ├── main.js ├── router.js ├── store │ ├── actions.js │ ├── index.js │ └── mutations.js └── views ├── ChatDashboard.vue └── Login.vue

For the loading-btn.css and the loading.css files, you can find them on the loading.io website. These files are not available in the npm repository, so you need to manually download them and place them in your project. Do make sure to read the documentation to get an idea on what they are and how to use the customizable loaders.

Next, we’re going to install the following dependencies:

@pusher/chatkit-client, a real-time client interface for the ChatKit service bootstrap-vue, a CSS framework moment, a date and time formatting utility vue-chat-scroll, which scrolls to the bottom automatically when new content is added vuex-persist, which saves Vuex state in browser’s local storage npm i @pusher/chatkit-client bootstrap-vue moment vue-chat-scroll vuex-persist

Do check out the links to learn more about what each package does, and how it can be configured.

Now, let’s configure our Vue.js project. Open src/main.js and update the code as follows:

import Vue from 'vue' import BootstrapVue from 'bootstrap-vue' import VueChatScroll from 'vue-chat-scroll' import App from './App.vue' import router from './router' import store from './store/index' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' import './assets/css/loading.css' import './assets/css/loading-btn.css' Vue.config.productionTip = false Vue.use(BootstrapVue) Vue.use(VueChatScroll) new Vue({ router, store, render: h => h(App) }).$mount('#app')

Update src/router.js as follows:

import Vue from 'vue' import Router from 'vue-router' import Login from './views/Login.vue' import ChatDashboard from './views/ChatDashboard.vue' Vue.use(Router) export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'login', component: Login }, { path: '/chat', name: 'chat', component: ChatDashboard, } ] })

Update src/store/index.js:

import Vue from 'vue' import Vuex from 'vuex' import VuexPersistence from 'vuex-persist' import mutations from './mutations' import actions from './actions' Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' const vuexLocal = new VuexPersistence({ storage: window.localStorage }) export default new Vuex.Store({ state: { }, mutations, actions, getters: { }, plugins: [vuexLocal.plugin], strict: debug })

The vuex-persist package ensures that our Vuex state is saved between page reloads or refreshes.

Our project should be able to compile now without errors. However, don’t run it just yet, as we need to build the user interface.

The post Build a Real-time Chat App with Pusher and Vue.js appeared first on SitePoint.

SitePoint Premium New Releases: Dev Tools, C# & Kubernetes

Jun 28, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Developer Essentials: Tools

In this short collection, we round up some of the best developer tools available, and provide some tips on how to improve your workflow with Gulp, and how to write better JavaScript.

➤ Read Developer Essentials: Tools.

Beginning C# 7 Programming with Visual Studio 2017

In this book, top ethical hackers discuss advanced persistent threats, public key encryption, firewalls, hacking cars, tools and techniques, social engineering, cryptography, penetration testing, network attacks, advice for parents of young hackers, the Code of Ethical Hacking, and much more.

➤ Read Beginning C# 7 Programming with Visual Studio 2017.

Kubernetes, Microservices and DevOps

A guided tour of container orchestration with Kubernetes. This Versioning Guide provides a guided reading list, curated by Versioning maestro Adam Roberts. It will cover installation, objects, cluster interaction, deployment and much more.

➤ Read Kubernetes, Microservices and DevOps.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Dev Tools, C# & Kubernetes appeared first on SitePoint.

The 9 Best Mind Mapping Tools for Designers

Jun 27, 2019

Description:

A Roundup of the Best Mind Mapping Tools

A mind map is a diagram drawn to help brainstorm ideas without being forced to organize or structure them. Instead, ideas are visually depicted in a hierarchical structure showing the flow and relationship between various ideas as they arise, which allows us to analyze them and recall them with ease.

Let’s take a look at the types of mind maps that are used in UX, and the mind mapping tools that are used to create them.

The Benefits of Mind Mapping

So, why mind map?

Ideation is exciting. Ideas here, ideas there. However, the enthusiasm to conceptualize them can be so invigorating that we don’t take the time to develop upon them or consider other ideas.

Rushing into a concept can take us down a road that’s seemingly harmless but actually quite dangerous. It might get us to finish line, which feels great, but with an end-result that’s mashup of random thoughts and ideas that don’t work together.

By mapping out ideas, we can better understand their:

value (what’s to be gained by exploring this idea?) role (how does the idea fit into the bigger picture?) relationships (how does the idea relate to other ideas?)

Eventually we can start to organize these ideas by similarity using a methodology called affinity mapping, which in turn helps us design user-centric mockups and wireframes as opposed to being driven by personal opinion.

How Mind Maps Are Used in UX

Mind maps can evolve into other types of maps with more specific uses. For example, maps that explore the navigational hierarchy and user flows of software systems such as websites, apps, and so on, are referred to as sitemaps. Maps that explore the numerous ways in which customers might interact with a product are called customer journey maps.

Both of these are useful when planning UX design projects — sitemaps for planning wireframes, and customer journey maps for optimizing the online and offline customer experience.

Coggle Pricing: $0, $5, or $8 (/month) Platform: web Pros: simple features, real-time collaboration Cons: looks a tad outdated, only accomplishes mind mapping

While many old-school mind mapping tools have become tragically outdated over the years, Coggle is one that’s managed to survive by keeping its focus solely on mind mapping and sporting a fairly simple user interface.

a Coggle mind map

It still looks somewhat dated, but nonetheless is much better looking than veteran tools like FreeMind (which hasn’t been updated in at least four years) and Mind Manager (which looks like it came bundled with Windows 95).

Check out the Coggle Mind Map Gallery, especially the mind map that describes the various types of emotion.

Notice how each emotion is divided by color, then further divided into more specific emotions depicted with capital letters, and then divided once more in a smaller font. It’s totally up to you how visually organize your thoughts and relationships. Coggle lets us explore ideas using images, branches, loops, shapes, and whatever else we need to explore our story.

Stakeholders can weigh in by commenting on mind maps, but also collaborate in real time as if using a whiteboard.

Apart from real-time collaboration, these features are standard and are included in every other tool in this list.

TL;DR: Coggle is everything you need, and nothing you don’t.

XMind Pricing: $1.24, $4.58, or $4.99 (/month) Platform: web, iOS, Android, macOS, Linux, Windows Pros: beautiful maps, very modern, excellent UX Cons: only mind mapping, no real-time collaboration

Other than Coggle, XMind is the only mind mapping tool to withstand the test of time, these days taking inspiration from critically acclaimed screen design tools like Sketch to offer a mighty mind mapping experience, but still with a minimalist and intuitive user interface. XMind mind maps look stunning, and while there’s no real-time collaboration, the maps can be shared with stakeholders and exported in a variety of formats.

An XMind map

If you’re looking for a modern-looking mind mapping tool without the bells and whistles, XMind is more than suitable.

Tip: try “Zen Mode” to remove all UI distractions!

The post The 9 Best Mind Mapping Tools for Designers appeared first on SitePoint.

How to Get Started with Vuetify

Jun 26, 2019

Description:

In this article, you will learn how you can quickly build an attractive and interactive frontend very quickly using Vuetify. Building a friendly application interface with a great user experience is a skill that requires practice and knowledge. While Vuetify won't make you a skilled UX practitioner over night, it will help provide a solid start to those who are new in this area.

As a Vue.js developer, there are many fully-featured CSS frameworks specifically developed for Vue that you can take advantage of. One great example is Bootstrap-Vue. I have used it and and it does really make building components easier than just using traditional CSS frameworks. However, you may want to give your apps a Material Design look and feel to make it familiar to new users.

According to the makers of Material Design:

"Material Design isn't a single style. It's an adaptable design system inspired by paper and ink. And engineered so you can build beautiful, usable products faster."

I hope I now have your attention with that powerful statement. Currently, Vuetify is the most complete user interface component library for Vue applications that follows the Google Material Design specs. Let's quickly dive in and look at how you can get started.

Prerequisites

This guide is written for developers who have intermediate or advanced knowledge of Vue.js. If you have never used Vue.js to build applications, please check out these articles:

Jump Start Vue, our complete introduction to Vue.js Getting Started with Vue.js — a quick primer Getting up and Running with the Vue.js 2.0 Framework More Vue.js Articles What is Vuetify?

Vuetify is an open source MIT project for building user interfaces for web and mobile applications. It is a project that is backed by sponsors and volunteers from the Vue community. The project is supported by a vibrant Discord community forum where you can ask JavaScript questions — even if they're not about Vuetify. The development team is committed to fixing bugs and providing enhancements through consistent update cycles. There are also weekly patches to fix issues that the community raises.

Most open-source frontend libraries don't get this level of attention. So you can be confident that when you start using Vuetify in your projects, you won't be left hanging without support in the future. Vuetify supports all major browsers out of the box. Older browsers such as IE11 and Safari 9 can work too but will require babel-polyfill. Anything older than that is not supported. Vuetify is built to be semantic. This means that every component and prop name you learn will be easy to remember and re-use without frequently checking the documentation.

Vuetify also comes with free/premium themes and pre-made layouts you can use to quickly theme your application. At the time of writing, Vuetify v1.5.13 is the current version, which utilizes Material Design Spec v1. Version 2.x of Vuetify will utilize Material Design Spec v2 which will soon be made available. Let's go over to the next section to see a couple of ways we can install Vuetify into our projects.

Installing Vuetify

If you already have an existing Vue project that was created with an older version of Vue CLI tool or some other way, you can simply install Vuetify as follows:

The post How to Get Started with Vuetify appeared first on SitePoint.

A Beginner’s Guide to Vue CLI

Jun 25, 2019

Description:

A Beginner’s Guide to Vue CLI

When building a new Vue app, the best way to get up and running quickly is to use Vue CLI. This is a command-line utility that allows you to choose from a range of build tools, which it will then install and configure for you. It will also scaffold out your project, providing you with a pre-configured starting point that you can build on, rather than starting everything from scratch.

The most recent version of Vue CLI is version 3. It provides a new experience for Vue developers and helps them start developing Vue apps without dealing with the complex configuration of tools like webpack. At the same time, it can be configured and extended with plugins for advanced use cases.

Vue CLI v3 is a complete system for rapid Vue.js development and prototyping. It’s composed of different components, such as the CLI service, CLI plugins and recently a web UI that allows developers to perform tasks via an easy-to-use interface.

Throughout this article, I’ll introduce the latest version of Vue CLI and its new features. I’ll demonstrate how to install the latest version of Vue CLI and how to create, serve and build an example project.

Vue CLI v3 Installation and Requirements

In this section, we’ll look at the requirements needed for Vue CLI v3 and how to install it.

Requirements

Let’s start with the requirements. Vue CLI v3 requires Node.js 8.9+, but v8.11.0+ is recommended.

You can install the latest version of Node.js in various ways:

By downloading the binaries for your system from the official website. By using the official package manager for your system. Using a version manager. This is probably the easiest way, as it allows you to manage multiple versions of Node on the same machine. If you’d like to find out more about this approach, please see our quick tip Installing Multiple Versions of Node.js Using nvm.

Vue creator, Evan You, described version 3 of the CLI as a “completely different beast” from its predecessor. As such, it’s important to uninstall any previous version of the CLI (that is, 2.x.x) before preceding with this tutorial.

If the vue-cli package is installed globally on your system, you can remove it by running the following command:

npm uninstall vue-cli -g Installing Vue CLI v3

You can now install Vue CLI v3 by simply running the following command from your terminal:

npm install -g @vue/cli

Note: if you find yourself needing to add sudo before your command in macOS or Debian-based systems, or to use an administrator CMD prompt in Windows in order to install packages globally, then you should fix your permissions. The npm site has a guide on how to do this, or just use a version manager and you avoid the problem completely.

After successfully installing the CLI, you’ll be able to access the vue executable in your terminal.

For example, you can list all the available commands by executing the vue command:

vue

You can check the version you have installed by running:

vue --version $ 3.2.1 Creating a Vue Project

After installing Vue CLI, let’s now look at how we can use it to quickly scaffold complete Vue projects with a modern front-end toolset.

Using Vue CLI, you can create or generate a new Vue app by running the following command in your terminal:

vue create example-vue-project

Tip: example-vue-project is the name of the project. You can obviously choose any valid name for your project.

The CLI will prompt you for the preset you want to use for your project. One option is to select the default preset which installs two plugins: Babel for transpiling modern JavaScript, and ESLint for ensuring code quality. Or you can manually select the features needed for your project from a set of official plugins. These include:

Babel TypeScript Progressive Web App support Vue Router Vuex (Vue’s official state management library) CSS Pre-processors (PostCSS, CSS modules, Sass, Less & Stylus) Linter/ Formatter using ESLint and Prettier Unit Testing using Mocha or Jest E2E Testing using Cypress or Nightwatch

Whatever you choose, the CLI will download the appropriate libraries and configure the project to use them. And if you choose to manually select features, at the end of the prompts you’ll also have the option to save your selections as a preset so that you can reuse it in future projects.

Now let’s look at the other scripts for serving the project (using a webpack development server and hot module reloading) and building the project for production.

Navigate inside your project’s folder:

cd example-vue-project

Next, run the following command to serve your project locally:

npm run serve

The command will allow you to run a local development server from the http://localhost:8080 address. If you use your web browser to navigate to this address, you should see the following page:

Welcome to Your Vue.js App

The development server supports features like hot code reloading, which means you don’t need to stop and start your server every time you make any changes to your project’s source code. It will even preserve the state of your app!

And when you’ve finished developing your project, you can use the following command to build a production bundle:

npm run build

This will output everything to a dist folder within your project. You can read more about deployment here.

What is the Vue CLI Service?

The Vue CLI Service is a run-time dependency (@vue/cli-service) that abstracts webpack and provides default configurations. It can be upgraded, configured and extended with plugins.

It provides multiple scripts for working with Vue projects, such as the serve, build and inspect scripts.

We’ve seen the serve and build scripts in action already. The inspect script allows you to inspect the webpack config in a project with vue-cli-service. Try it out:

vue inspect

As you can see, that produces a lot of output. Later on we’ll see how to tweak the webpack config in a Vue CLI project.

The Project Anatomy

A Vue project generated with the CLI has a predefined structure that adheres to best practices. If you choose to install any extra plugins (such as the Vue router), the CLI will also create the files necessary to use and configure these libraries.

Let’s take a look at the important files and folders in a Vue project when using the default preset.

public. This folder contains public files like index.html and favicon.ico. Any static assets placed here will simply be copied and not go through webpack. src. This folder contains the source files for your project. Most work will be done here. src/assets. This folder contains the project’s assets such as logo.png. src/components. This folder contains the Vue components. src/App.vue. This is the main Vue component of the project. src/main.js. This is the main project file which bootstraps the Vue application. babel.config.js. This is a configuration file for Babel. package.json. This file contains a list of the project’s dependencies, as well as the configuration options for ESLint, PostCSS and supported browsers. node_modules. This folder contains the installed npm packages.

This is a screenshot of the project’s anatomy:

Project anatomy

Vue CLI Plugins

Vue CLI v3 is designed with a plugin architecture in mind. In this section, we’ll look at what plugins are and how to install them in your projects. We’ll also look at some popular plugins that can help add advanced features by automatically installing the required libraries and making various settings—all of which would otherwise have to be done manually.

What a Vue Plugin Is

CLI Plugins are just npm packages that provide additional features to your Vue project. The vue-cli-service binary automatically resolves and loads all plugins listed in the package.json file.

The base configuration for a Vue CLI 3 project is webpack and Babel. All the other features can be added via plugins.

There are official plugins provided by the Vue team and community plugins developed by the community. Official plugin names start with @vue/cli-plugin-, and community plugin names start with vue-cli-plugin-.

Official Vue CLI 3 plugins include:

Typescript PWA Vuex Vue Router ESLint Unit testing etc. How to Add a Vue Plugin

Plugins are either automatically installed when creating the project or explicitly installed later by the developer.

You can install many built-in plugins in a project when initializing your project, and install any other additional plugins in the project using the vue add my-plugin command at any point of your project.

You can also install plugins with presets, and group your favorite plugins as reusable presets that you can use later as the base for other projects.

Some Useful Vue Plugins

There are many Vue CLI plugins that you might find useful for your next projects. For example, the Vuetify UI library is available as a plugin, as is Storybook. You can also use the Electron Builder plugin to quickly scaffold out a Vue project based on Electron.

I’ve also written a couple of plugins which you can make use of:

vue-cli-plugin-nuxt: a Vue CLI plugin for quickly creating a universal Vue application with Nuxt.js vue-cli-plugin-bootstrap: a Vue CLI plugin for adding Bootstrap 4 to your project

If you’d like to find out more about plugins, check out this great article on Vue Mastery: 5 Vue CLI 3 plugins for your Vue project.

The post A Beginner’s Guide to Vue CLI appeared first on SitePoint.

30+ Web Tools and Services to Help You Launch Your Next Big Thing

Jun 25, 2019

Description:

Do something great neon sign

This article was created in partnership with Mekanism. Thank you for supporting the partners who make SitePoint possible.

2019 is the best year to become successful, to launch your own online or offline business, to invent a product or service, or to grow your business into a huge corporation. Because to sketch, test, build and launch that business that will become the next Uber, Instagram, or Waze is now easier than ever before.

The difference between now and previous years, is that there are now a plethora of web tools and services to help you launch your next big thing - some of them are even free! Today anybody can build a website or logo without any specialist knowledge or previous experience. With only a few hours investment, you can get amazing results. It's a quick and affordable way to get your site or product to market.

In this article we are going to review 36 different web tools and services that are recommended by successful people. Each of them will save you time and money, or help improve your business and workflows, so you can get on with launching and scaling.

1. Creative-TIM - Premium Bootstrap Themes and Templates

Creative Tim

Creative Tim is the perfect place where web designers and web developers can find fully coded UI tools to help you build web and mobile apps. With over 750.000 users, Creative Tim offers UI Kits, Dashboards and Design Systems.

All the development is made on top of Bootstrap 4: Vuejs, Angular, React, React Native. Using these tools will save developers and designers hours of work since the products already contain a large number of components and are packed with all the plugins that you might need on a project. Everything used to create the products can be downloaded for free under the MIT License.

For people with many upcoming projects, Creative Tim offers 6 Bundles at special prices, to encourage developers to save precious time and to trust the quality of their projects.
Last but not least, Creative Tim’s products are used not only by thousands of freelancers and developers but by top companies like NASA, Cisco, IBM, and Amazon.

Check out their website and find the product that matches your needs.
Pricing: Free to $249

2. Brizy - Innovative Site Builder

Brizy

Brizy is the most user-friendly visual page builder in town! No designer or developer skills required. The only tools you'll need to master are clicks and drags.

Brizy can be used two ways. One is to download the WordPress plugin and use it as such, and the next one is the Cloud platform where you can create landing pages in minutes. From hosting to domain setups Brizy handles everything. Brizy Cloud is included with any Brizy PRO plan.

Creating a powerful, fully functional website is extremely easy with Brizy and anybody can do it without having any designer’s skills or writing a single line of code. This website builder has the most powerful features included, both for the free and paid plans. The free account will bring you premium features that you have to pay for on other website builders. At Brizy, these features are free.

Build a free website with Brizy today, the process is very fast and intuitive.

3. Tailor Brands

Tailor Brands

Tailor Brands is a revolutionary online logo and branding platform that will help you design your logo in seconds. It has over 10 million users and counting, and it was used to create over 400 million designs. Every second 1 a new design is made via it.

This AI-powered online logo maker platform does not use pre-made logo templates. Every design is uniquely crafted to match your business and brand personality perfectly. You don’t need to have any design skills or special knowledge, it is super simple to use and extremely fast.

Write down the logo name you want, make a few selections from the options provided by Tailor Brands and you will get a number of designs to choose from.

4. 48HoursLogo – Affordable Logos Done Fast

48HoursLogo

48hourslogo is a fast, easy and very affordable logo crowdsourcing website that has created over 3 million logos. With contest prizes starting at just $99, more than 40,000 small businesses and entrepreneurs have used this amazing logo design service to get gorgeous and creative designs.

After launching your logo design contest at 48hourslogo, your project will go through 3 stages before arriving at your final design. The qualifying stage: the contest is open to all registered designers and they will submit multiple logo concepts for you to choose from. The design revision stage: at the end of qualifying stage, you will be prompted to select up to 3 finalist designers to enter the “design revision stage”. And at the end, the finalizing stage: after selecting your contest winner, you will work with your winning designer on finalizing your design, (you can still request small changes and tweaks to your winning logo).

Start a logo design contest using 48hourslogo.

5. Codester

Codester.com

Codester is a huge marketplace where web designers and web developers will find tons of premium PHP scripts, app templates, themes, plugins and much more.

Always check the Flash Sales section where hugely discounted items are being sold.

Browse Codester and pick the items you need.

6. NameQL

NameQL

NameQL helps you find a great name. It considers thousands of potential names in milliseconds and shows you the best ones that are still available for purchase as [name].com. It'sa huge time saver whenever you are looking for a new website domain name.

7. SeekVisa

Seekvisa

Australia is a great destination to live and work, with developers, software engineers and user experience/user interface designer in high demand. If you're considering immigrating to Australia, you can discuss with SeekVisa, who are migration experts.

Australia's Employer Nomination Scheme (ENS) enables Australian employers to sponsor highly skilled workers to live and work permanently in Australia. This is the quickest way for IT developers to immigrate to Australia. Contact Seekvisa to determine your eligibility.

8. MobiLoud

MobiLoud

Publishers are seeing up to 90% of their traffic coming from mobile. Mobile apps give readers the experience they want and let publishers increase engagement, traffic, and revenue.

With fast loading times, your app encourages loyalty and repeat visits. With push notifications, it brings people back again and again. Your icon is a constant reminder of your brand and content.

MobiLoud is the best solution for news mobile apps built on WordPress. They will publish and maintain your custom app, with push notifications, advertising and subscriptions, all at a fraction of the time and cost of traditional app development.

The post 30+ Web Tools and Services to Help You Launch Your Next Big Thing appeared first on SitePoint.

Code Challenge #2: 4 Tips for Higher Scores in CSSBattle.dev

Jun 24, 2019

Description:

Our CSSBattle Code Challenge requires some 'outside the square' CSS thinking. Here are four pro tips to get you started on the right track.

The post Code Challenge #2: 4 Tips for Higher Scores in CSSBattle.dev appeared first on SitePoint.

How to Set Up a Mobile Development Environment

Jun 21, 2019

Description:

The use of mobile devices has increased considerably in the past decade. It has been over two years since mobile browsing took over desktop. The usability of mobile devices has exploded, too. Mobile devices now come with huge processing power.

We often dismiss mobile platforms as serious workhorses for developers, but today, it's possible to take advantage of mobile portability with a level of flexibility that gets closer to the desktop every year.

This post explains the process of running a Linux development environment from your mobile device using Samsung Dex.

A Brief History of Samsung Dex

Samsung Dex is a platform that allows you to use the computing power of your mobile device to run a desktop-like environment. It was introduced in 2017 and has been actively developed since. The number of devices that can run Dex has increased steadily. In this post, we explore how to set up a Linux development environment through Samsung Dex.

The post How to Set Up a Mobile Development Environment appeared first on SitePoint.

SitePoint Premium New Releases: Cybersecurity & DevOps Adoption

Jun 21, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

The DevOps Adoption Playbook

This award-winning book provides actionable, real-world guidance on implementing DevOps in large-scale enterprise IT environments, explaining how to achieve high-value innovation and optimization with low cost and risk, and exceed traditional business goals with higher product release efficiency.

➤ Read The DevOps Adoption Playbook.

Hacking the Hacker

In this book, top ethical hackers discuss advanced persistent threats, public key encryption, firewalls, hacking cars, tools and techniques, social engineering, cryptography, penetration testing, network attacks, advice for parents of young hackers, the Code of Ethical Hacking, and much more.

➤ Read Hacking the Hacker.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Cybersecurity & DevOps Adoption appeared first on SitePoint.

7 Worst UX Mistakes Limiting Your Growth

Jun 19, 2019

Description:

Growth. Growth! GROWTH!

Growth is often the top focus for businesses that are “onto something.” They’ve found what makes customers tick, their special recipe, and now they’re ready for the world to see.

However, scaling doesn’t only scale success.

If there’s friction in the UX, bugs, technical limitations, or any other types of UX flaws, these flaws are magnified as a product scales, which is why the most successful businesses are the ones that take their time and try not to grow too rapidly.

It’s why software teams build for one platform at a time, and it’s why MVPs and betas are only available to a subset of users.

Let’s take a look at some of the worst UX mistakes we’ll really, really want to avoid while trying to “scale up” our businesses.

1. Time Wasting

The majority of design decisions will have only a small impact. Sure, collectively, these decisions may amount to improved UX, but only one in a few will have a detrimental effect on growth.

Also, UX design is not a task. UX design is a continuous effort, and attempting to solve everything all at once can result in stress, anxiety, OCD, and eventually severe burnout.

Perfectionism is a serious growth-stopper.

The fact is, some design changes will skyrocket conversions whereas others will be much less effective, but it is really easy to obsess over these tiny details. A fantastic way to approach this is to tackle design in short, focused bursts using well-known design methodologies such as the design sprint. Design sprints help to identify problems, reframe them as opportunities, and then decide which of the problems might yield the best results, if solved.

In short, don’t waste too much time on the small things by focusing on the high-growth opportunities first. This ensures that we’re tackling the bigger problems while not creating too many bugs and flaws, as too many can be a serious hindrance.

2. Focusing on Pixels

Performance, meaning, how fast the app or website feels and loads, is a vital aspect of the user experience. While this is a task typically assigned to developers, designers should remember that it’s they who’ll design what’s to be implemented, which is why we’d recommend working design handoff tools into the workflow.

The post 7 Worst UX Mistakes Limiting Your Growth appeared first on SitePoint.

Getting Started with Vuex: a Beginner’s Guide

Jun 18, 2019

Description:

Getting Started with Vuex: a Beginner’s Guide

In single-page applications, the concept of state relates to any piece of data that can change. An example of state could be the details of a logged-in user, or data fetched from an API.

Handling state in single-page apps can be a tricky process. As an application gets larger and more complex, you start to encounter situations where a given piece of state needs to be used in multiple components, or you find yourself passing state through components that don’t need it, just to get it to where it needs to be. This is also known as “prop drilling”, and can lead to some unwieldy code.

Vuex is the official state management solution for Vue. It works by having a central store for shared state, and providing methods to allow any component in your application to access that state. In essence, Vuex ensures your views remain consistent with your application data, regardless of which function triggers a change to your application data.

In this article, I’ll offer you a high-level overview of Vuex and demonstrate how to implement it into a simple app.

A Shopping Cart Example

Let’s consider a real-world example to demonstrate the problem that Vuex solves.

When you go to a shopping site, you’ll usually have a list of products. Each product has an Add to Cart button and sometimes an Items Remaining label indicating the current stock or the maximum number of items you can order for the specified product. Each time a product is purchased, the current stock of that product is reduced. When this happens, the Items Remaining label should update with the correct figure. When the product’s stock level reaches 0, the label should read Out of Stock. In addition, the Add to Cart button should be disabled or hidden to ensure customers can’t order products that are currently not in inventory.

Now ask yourself how you’d implement this logic. It may be trickier than you think. And let me throw in a curve ball. You’ll need another function for updating stock records when new stock comes in. When the depleted product’s stock is updated, both the Items Remaining label and the Add to Cart button should be updated instantly to reflect the new state of the stock.

Depending on your programming prowess, your solution may start to look a bit like spaghetti. Now, let’s imagine your boss tells you to develop an API that allows third-party sites to sell the products directly from the warehouse. The API needs to ensure that the main shopping website remains in sync with the products’ stock levels. At this point you feel like pulling your hair out and demanding why you weren’t told to implement this earlier. You feel like all your hard work has gone to waste, as you’ll need to completely rework your code to cope with this new requirement.

This is where a state management pattern library can save you from such headaches. It will help you organize the code that handles your front-end data in a way that makes adding new requirements a breeze.

Prerequisites

Before we start, I’ll assume that you:

have a basic knowledge of Vue.js are familiar with ES6 and ES7 language features

You’ll also need to have a recent version of Node.js that’s not older than version 6.0. At the time of writing, Node.js v10.13.0 (LTS) and npm version 6.4.1 are the most recent. If you don’t have a suitable version of Node installed on your system already, I recommend using a version manager.

Finally, you should have the most recent version of the Vue CLI installed:

npm install -g @vue/cli Build a Counter Using Local State

In this section, we’re going to build a simple counter that keeps track of its state locally. Once we’re done, I’ll go over the fundamental concepts of Vuex, before looking at how to rewrite the counter app to use Vue’s official state management solution.

Getting Set Up

Let’s generate a new project using the CLI:

vue create vuex-counter

A wizard will open up to guide you through the project creation. Select Manually select features and ensure that you choose to install Vuex.

Next, change into the new directory and in the src/components folder, rename HelloWorld.vue to Counter.vue:

cd vuex-counter mv src/components/HelloWorld.vue src/components/Counter.vue

Finally, open up src/App.vue and replace the existing code with the following:

<template> <div id="app"> <h1>Vuex Counter</h1> <Counter/> </div> </template> <script> import Counter from './components/Counter.vue' export default { name: 'app', components: { Counter } } </script>

You can leave the styles as they are.

Creating the Counter

Let’s start off by initializing a count and outputting it to the page. We’ll also inform the user whether the count is currently even or odd. Open up src/components/Counter.vue and replace the code with the following:

<template> <div> <p>Clicked {{ count }} times! Count is {{ parity }}.</p> </div> </template> <script> export default { name: 'Counter', data: function() { return { count: 0 }; }, computed: { parity: function() { return this.count % 2 === 0 ? 'even' : 'odd'; } } } </script>

As you can see, we have one state variable called count and a computed function called parity which returns the string even or odd depending on the whether count is an odd or even number.

To see what we’ve got so far, start the app from within the root folder by running npm run serve and navigate to http://localhost:8080.

Feel free to change the value of the counter to show that the correct output for both counter and parity is displayed. When you’re satisfied, make sure to reset it back to 0 before we proceed to the next step.

Incrementing and Decrementing

Right after the computed property in the <script> section of Counter.vue, add this code:

methods: { increment: function () { this.count++; }, decrement: function () { this.count--; }, incrementIfOdd: function () { if (this.parity === 'odd') { this.increment(); } }, incrementAsync: function () { setTimeout(() => { this.increment() }, 1000) } }

The first two functions, increment and decrement, are hopefully self-explanatory. The incrementIfOdd function only executes if the value of count is an odd number, whereas incrementAsync is an asynchronous function that performs an increment after one second.

In order to access these new methods from the template, we’ll need to define some buttons. Insert the following after the template code which outputs the count and parity:

<button @click="increment" variant="success">Increment</button> <button @click="decrement" variant="danger">Decrement</button> <button @click="incrementIfOdd" variant="info">Increment if Odd</button> <button @click="incrementAsync" variant="warning">Increment Async</button>

After you’ve saved, the browser should refresh automatically. Click all of the buttons to ensure everything is working as expected. This is what you should have ended up with:

See the Pen Vue Counter Using Local State by SitePoint (@SitePoint) on CodePen.

The counter example is now complete. Let’s move and examine the fundamentals of Vuex, before looking at how we would rewrite the counter to implement them.

How Vuex Works

Before we go over the practical implementation, it’s best that we acquire a basic grasp of how Vuex code is organized. If you’re familiar with similar frameworks such as Redux, you shouldn’t find anything too surprising here. If you haven’t dealt with any Flux-based state management frameworks before, please pay close attention.

The Vuex Store

The store provides a centralized repository for shared state in Vue apps. This is what it looks like in its most basic form:

// src/store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { // put variables and collections here }, mutations: { // put sychronous functions for changing state e.g. add, edit, delete }, actions: { // put asynchronous functions that can call one or more mutation functions } })

After defining your store, you need to inject it into your Vue.js application like this:

// src/main.js import store from './store' new Vue({ store, render: h => h(App) }).$mount('#app')

This will make the injected store instance available to every component in our application as this.$store.

Working with State

Also referred to as the single state tree, this is simply an object that contains all front-end application data. Vuex, just like Redux, operates using a single store. Application data is organized in a tree-like structure. Its construction is quite simple. Here’s an example:

state: { products: [], count: 5, loggedInUser: { name: 'John', role: 'Admin' } }

Here we have products that we’ve initialized with an empty array, and count, which is initialized with the value 5. We also have loggedInUser, which is a JavaScript object literal containing multiple fields. State properties can contain any valid datatype from Booleans, to arrays, to other objects.

There are multiple ways to display state in our views. We can reference the store directly in our templates using $store:

<template> <p>{{ $store.state.count }}</p> </template>

Or we can return some store state from within a computed property:

<template> <p>{{ count }}</p> </template> <script> export default { computed: { count() { return this.$store.state.count; } } } </script>

Since Vuex stores are reactive, whenever the value of $store.state.count changes, the view will change as well. All this happens behind the scenes, making your code look simple and cleaner.

The mapState Helper

Now, suppose you have multiple states you want to display in your views. Declaring a long list of computed properties can get verbose, so Vuex provides a mapState helper. This can be used to generate multiple computed properties easily. Here’s an example:

<template> <div> <p>Welcome, {{ loggedInUser.name }}.</p> <p>Count is {{ count }}.</p> </div> </template> <script> import { mapState } from 'vuex'; export default { computed: mapState({ count: state => state.count, loggedInUser: state => state.loggedInUser }) } </script>

Here’s an even simpler alternative where we can pass an array of strings to the mapState helper function:

export default { computed: mapState([ 'count', 'loggedInUser' ]) }

This version of the code and the one above it do exactly the same thing. You should note that mapState returns an object. If you want to use it with other computed properties, you can use the spread operator. Here’s how:

computed: { ...mapState([ 'count', 'loggedInUser' ]), parity: function() { return this.count % 2 === 0 ? 'even' : 'odd' } }

The post Getting Started with Vuex: a Beginner’s Guide appeared first on SitePoint.

SitePoint Premium New Releases: SSGs, Interaction Design, Node & Vue

Jun 14, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

An Introduction to Hexo

In this guide we'll present Hexo, an open-source static site generator suitable for building blogs and documentation websites. We'll cover installation, working with layouts, generating posts and providing content, customizing and installing third-party themes, and deploying to Heroku.

➤ Read An Introduction to Hexo.

About Face

This essential interaction design guide examines mobile apps, touch interfaces and screen size considerations, examining goal-directed design methodology, product design methods, design for mobile platforms and consumer electronics, contemporary interfaces, interface recommendations, and much more.

➤ Read About Face.

Drupal 8 Development Cookbook Second Edition

Discover the enhanced content authoring experience that comes with Drupal 8 and how to customize it. Take advantage of multilingual tools for providing an internationalized website. Learn how to deploy from development, staging, and production with Drupal's config management system.

➤ Read Drupal 8 Development Cookbook Second Edition.

A Beginner’s Guide to Creating a Static Website with Hugo

This tutorial describes how to use Hugo, a static site generator (SSG) written in Go. Hugo boasts rich features, is very quick thanks to Go, and has lots of third-party themes, an active community, and detailed documentation.

➤ Read A Beginner’s Guide to Creating a Static Website with Hugo.

RESTful Web API Design with Node.js 10 - Third Edition

Design and implement scalable and maintainable RESTful solutions with Node.js 10 from scratch. Explore the new features of Node.js 10, Express 4.0, and MongoDB. Integrate MongoDB in your Node.js application to store and secure your data.

➤ Read RESTful Web API Design with Node.js 10 - Third Edition.

Learn Vue.js: The Collection

For those of you looking for a comprehensive guide on Vue.js, we've made our collection available as a Kindle book on Amazon. It's a great companion to Jump Start Vue.js!

Since its release in 2014, Vue.js has seen a meteoric rise to popularity and is is now considered one of the primary front-end frameworks, and not without good reason. Its component-based architecture was designed to be flexible and easy to adopt, making it just as easy to integrate into projects and use alongside non-Vue code as it is to build complex client-side applications.

➤ Buy Learn Vue.js: The Collection.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: SSGs, Interaction Design, Node & Vue appeared first on SitePoint.

A Deep Dive into Redux

Jun 13, 2019

Description:

A Deep Dive into Redux

Building stateful modern applications is complex. As state mutates, the app becomes unpredictable and hard to maintain. That's where Redux comes in. Redux is a lightweight library that tackles state. Think of it as a state machine.

In this article, I’ll delve into Redux’s state container by building a payroll processing engine. The app will store pay stubs, along with all the extras — such as bonuses and stock options. I’ll keep the solution in plain JavaScript with TypeScript for type checking. Since Redux is super testable, I’ll also use Jest to verify the app.

For the purposes of this tutorial, I’ll assume a moderate level of familiarity with JavaScript, Node, and npm.

To begin, you can initialize this app with npm:

npm init

When asked about the test command, go ahead and put jest. This means npm t will fire up Jest and run all unit tests. The main file will be index.js to keep it nice and simple. Feel free to answer the rest of the npm init questions to your heart’s content.

I’ll use TypeScript for type checking and nailing down the data model. This aids in conceptualizing what we’re trying to build.

To get going with TypeScript:

npm i typescript --save-dev

I’ll keep dependencies that are part of the dev workflow in devDependencies. This makes it clear which dependencies are for developers and which goes to prod. With TypeScript ready, add a start script in the package.json:

"start": "tsc && node .bin/index.js"

Create an index.ts file under the src folder. This separates source files from the rest of the project. If you do an npm start, the solution will fail to execute. This is because you’ll need to configure TypeScript.

Create a tsconfig.json file with the following configuration:

{ "compilerOptions": { "strict": true, "lib": ["esnext", "dom"], "outDir": ".bin", "sourceMap": true }, "files": [ "src/index" ] }

I could have put this configuration in a tsc command-line argument. For example, tsc src/index.ts --strict .... But it’s much cleaner to go ahead and put all this in a separate file. Note the start script in package.json only needs a single tsc command.

Here are sensible compiler options that will give us a good starting point, and what each option means:

strict: enable all strict type checking options, i.e., --noImplicitAny, --strictNullChecks, etc. lib: list of library files included in the compilation outDir: redirect output to this directory sourceMap: generate source map file useful for debugging files: input files fed to the compiler

Because I’ll be using Jest for unit testing, I'll go ahead and add it:

npm i jest ts-jest @types/jest @types/node --save-dev

The ts-jest dependency adds type checking to the testing framework. One gotcha is to add a jest configuration in package.json:

"jest": { "preset": "ts-jest" }

This makes it so the testing framework picks up TypeScript files and knows how to transpile them. One nice feature with this is you get type checking while running unit tests. To make sure this project is ready, create a __tests__ folder with an index.test.ts file in it. Then, do a sanity check. For example:

it('is true', () => { expect(true).toBe(true); });

Doing npm start and npm t now runs without any errors. This tells us we’re now ready to start building the solution. But before we do, let’s add Redux to the project:

npm i redux --save

This dependency goes to prod. So, no need to include it with --save-dev. If you inspect your package.json, it goes in dependencies.

Payroll Engine in Action

The payroll engine will have the following: pay, reimbursement, bonus, and stock options. In Redux, you can’t directly update state. Instead, actions are dispatched to notify the store of any new changes.

So, this leaves us with the following action types:

const BASE_PAY = 'BASE_PAY'; const REIMBURSEMENT = 'REIMBURSEMENT'; const BONUS = 'BONUS'; const STOCK_OPTIONS = 'STOCK_OPTIONS'; const PAY_DAY = 'PAY_DAY';

The PAY_DAY action type is useful for dolling out a check on pay day and keeping track of pay history. These action types guide the rest of the design as we flesh out the payroll engine. They capture events in the state lifecycle — for example, setting a base pay amount. These action events can attach to anything, whether that be a click event or a data update. Redux action types are abstract to the point where it doesn’t matter where the dispatch comes from. The state container can run both on the client and/or server.

TypeScript

Using type theory, I’ll nail down the data model in terms of state data. For each payroll action, say an action type and an optional amount. The amount is optional, because PAY_DAY doesn’t need money to process a paycheck. I mean, it could charge customers but leave it out for now (maybe introducing it in version two).

So, for example, put this in src/index.ts:

interface PayrollAction { type: string; amount?: number; }

For pay stub state, we need a property for base pay, bonus, and whatnot. We’ll use this state to maintain a pay history as well.

This TypeScript interface ought to do it:

interface PayStubState { basePay: number; reimbursement: number; bonus: number; stockOptions: number; totalPay: number; payHistory: Array<PayHistoryState>; }

The PayStubState is a complex type, meaning it depends on another type contract. So, define the payHistory array:

interface PayHistoryState { totalPay: number; totalCompensation: number; }

With each property, note TypeScript specifies the type using a colon. For example, : number. This settles the type contract and adds predictability to the type checker. Having a type system with explicit type declarations enhances Redux. This is because the Redux state container is built for predictable behavior.

This idea isn’t crazy or radical. Here’s a good explanation of it in Learning Redux, Chapter 1 (SitePoint Premium members only).

As the app mutates, type checking adds an extra layer of predictability. Type theory also aids as the app scales because it’s easier to refactor large sections of code.

Conceptualizing the engine with types now helps to create the following action functions:

export const processBasePay = (amount: number): PayrollAction => ({type: BASE_PAY, amount}); export const processReimbursement = (amount: number): PayrollAction => ({type: REIMBURSEMENT, amount}); export const processBonus = (amount: number): PayrollAction => ({type: BONUS, amount}); export const processStockOptions = (amount: number): PayrollAction => ({type: STOCK_OPTIONS, amount}); export const processPayDay = (): PayrollAction => ({type: PAY_DAY});

What’s nice is that, if you attempt to do processBasePay('abc'), the type checker barks at you. Breaking a type contract adds unpredictability to the state container. I’m using a single action contract like PayrollAction to make the payroll processor more predictable. Note amount is set in the action object via an ES6 property shorthand. The more traditional approach is amount: amount, which is long-winded. An arrow function, like () => ({}), is one succinct way to write functions that return an object literal.

Reducer as a Pure Function

The reducer functions need a state and an action parameter. The state should have an initial state with a default value. So, can you imagine what our initial state might look like? I’m thinking it needs to start at zero with an empty pay history list.

For example:

const initialState: PayStubState = { basePay: 0, reimbursement: 0, bonus: 0, stockOptions: 0, totalPay: 0, payHistory: [] };

The type checker makes sure these are proper values that belong in this object. With the initial state in place, begin creating the reducer function:

export const payrollEngineReducer = ( state: PayStubState = initialState, action: PayrollAction): PayStubState => {

The Redux reducer has a pattern where all action types get handled by a switch statement. But before going through all switch cases, I’ll create a reusable local variable:

let totalPay: number = 0;

Note that it’s okay to mutate local variables if you don’t mutate global state. I use a let operator to communicate this variable is going to change in the future. Mutating global state, like the state or action parameter, causes the reducer to be impure. This functional paradigm is critical because reducer functions must remain pure. If you’re struggling with this paradigm, check out this explanation from JavaScript Novice to Ninja, Chapter 11 (SitePoint Premium members only).

Start the reducer’s switch statement to handle the first use case:

switch (action.type) { case BASE_PAY: const {amount: basePay = 0} = action; totalPay = computeTotalPay({...state, basePay}); return {...state, basePay, totalPay};

I’m using an ES6 rest operator to keep state properties the same. For example, ...state. You can override any properties after the rest operator in the new object. The basePay comes from destructuring, which is a lot like pattern matching in other languages. The computeTotalPay function is set as follows:

const computeTotalPay = (payStub: PayStubState) => payStub.basePay + payStub.reimbursement + payStub.bonus - payStub.stockOptions;

Note you deduct stockOptions because the money will go towards buying company stock. Say you want to process a reimbursement:

case REIMBURSEMENT: const {amount: reimbursement = 0} = action; totalPay = computeTotalPay({...state, reimbursement}); return {...state, reimbursement, totalPay};

Since amount is optional, make sure it has a default value to reduce mishaps. This is where TypeScript shines, because the type checker picks up on this pitfall and barks at you. The type system knows certain facts so it can make sound assumptions. Say you want to process bonuses:

case BONUS: const {amount: bonus = 0} = action; totalPay = computeTotalPay({...state, bonus}); return {...state, bonus, totalPay};

This pattern makes the reducer readable because all it does is maintain state. You grab the action’s amount, compute total pay, and create a new object literal. Processing stock options is not much different:

case STOCK_OPTIONS: const {amount: stockOptions = 0} = action; totalPay = computeTotalPay({...state, stockOptions}); return {...state, stockOptions, totalPay};

For processing a paycheck on pay day, it’ll need to blot out bonus and reimbursement. These two properties don’t remain in state per paycheck. And, add an entry to pay history. Base pay and stock options can stay in state because they don’t change as often per paycheck. With this in mind, this is how PAY_DAY goes:

case PAY_DAY: const {payHistory} = state; totalPay = state.totalPay; const lastPayHistory = payHistory.slice(-1).pop(); const lastTotalCompensation = (lastPayHistory && lastPayHistory.totalCompensation) || 0; const totalCompensation = totalPay + lastTotalCompensation; const newTotalPay = computeTotalPay({...state, reimbursement: 0, bonus: 0}); const newPayHistory = [...payHistory, {totalPay, totalCompensation}]; return {...state, reimbursement: 0, bonus: 0, totalPay: newTotalPay, payHistory: newPayHistory};

In an array like newPayHistory, use a spread operator, which is the reverse of rest. Unlike rest, which collects properties in an object, this spreads items out. So, for example, [...payHistory]. Even though both these operators look similar, they aren’t the same. Look closely, because this might come up in an interview question.

Using pop() on payHistory doesn’t mutate state. Why? Because slice() returns a brand new array. Arrays in JavaScript are copied by reference. Assigning an array to a new variable doesn’t change the underlying object. So, one must be careful when dealing with these types of objects.

Because there’s a chance lastPayHistory is undefined, I use poor man’s null coalescing to initialize it to zero. Note the (o && o.property) || 0 pattern to coalesce. Maybe a future version of JavaScript or even TypeScript will have a more elegant way of doing this.

Every Redux reducer must define a default branch. To make sure state doesn’t become undefined:

default: return state;

The post A Deep Dive into Redux appeared first on SitePoint.

Code Challenge #2: The Test of Characters

Jun 13, 2019

Description:

CSSBattles.dev

I’ve been a big fan Kushagra Gour since the early days of Webmaker – his CodePen-like code playground running as a Chrome Extension. I use it most days. More recently he teamed up Kushagra Agarwal to work on a new project ‘CSSBattle.dev‘ – a cool and original blend of CSS coding and golf. Be warned […]

The post Code Challenge #2: The Test of Characters appeared first on SitePoint.

So, Do We Have a Winner for Code Challenge #1?

Jun 13, 2019

Description:

It’s been a week since we launched our quick Code Challenge #1, which means it’s time to announce a winner! It was tricky. While the quantity of entries wasn’t high, there’s no questioning the quality of our winning entries. But first, let’s run through a few different approaches to the challenge we supplied. My turn […]

The post So, Do We Have a Winner for Code Challenge #1? appeared first on SitePoint.

10 Top Chrome Extensions for Your Web Development Workflow

Jun 12, 2019

Description:

As web developers we work in a very fast paced industry and staying on top of things can sometimes be a challenge. That's why I believe we should take full advantage of whatever tools we have at our disposal to help keep our heads above water. Today I'm going to present ten Chrome extensions that are geared to optimizing your web development workflow, hopefully making you that little bit more productive.

What are Chrome Extensions?

As can be read on Chrome's developer portal, extensions are small software programs that can customize your browsing experience. This can be anything from a spelling and grammar checker that checks your writing as you type, to a password manager that saves your login details for your favorite sites.

There are literally thousands of extensions available for Chrome, all of which can be downloaded for free from the Chrome Web Store. You can check which extensions you currently have installed by visiting the following link in your browser: chrome://extensions/.

Why Chrome?

This article focuses on the Google Chrome browser due to its huge market share (currently 65% and rising). There are also many Chrome-based browsers which support extensions. These include Brave, Vivaldi and, coming soon, Microsoft Edge. However, we should remember that Chrome isn't the only show in town and that many of the extensions mentioned here have a Firefox and/or Opera equivalent.

Finally, before we dive into the extensions, take a minute to remember that Chrome is proprietary software published by Google. As we all know, there are privacy concerns associated with using Google products, so maybe head over to GitHub and check out the ungoogled-chromium project instead. As the name suggests, this is Google Chromium, sans integration with Google.

1. Web Developer

We'll start off with the Swiss Army knife of extensions. With over 1 million users and a 4.5 star rating on the Chrome Web Store, Web Developer is something of a must have. It adds a toolbar button to Chrome which, when clicked, displays a plethora of tools that can be used on any web page. These are grouped by category (CSS, forms, images etc) and allow you to do such things as disable JavaScript, outline images with missing alt attributes, resize the browser window, validate a page's HTML, view a page's meta tag information and much more.

Web Developer Chrome extension

You can download it here.

2. Your Framework's Developer Tools

If you're developing an app with a JavaScript framework and you're not using that framework's developer tools, then you're probably doing it wrong. Let me explain using Vue as an example.

If you have a Vue app which you need to debug, or you just want to see what's going on under the hood, then what do you do? Inspecting the page's source will show you the HTML that Vue is rendering, but there is much more to a Vue app than that. What about a component's props, data or computed properties? Or your app's state or routing? How do you inspect any of those?

The good news is that the Vue.js dev tools have you covered. Simply install the extension and open it up on a page running a development build of Vue to see exactly what is happening in your app.

Vue.js Dev Tools

Here are links to download the dev tools for the big three frameworks.

Vue React Ember 3. Daily 2.0 - Source for Busy Developer

As we work in a fast paced industry, keeping up with news and goings on can sometimes be a challenge. Enter Daily 2.0, an extension that gathers the latest web development and tech posts from around the internet and presents them in an attractive masonry-style lay out on your new tab page.

The extension is easy to use. When you install it you are asked to pick from a bunch of categories that interest you and Daily 2.0 does the rest. Hovering over the sidebar on the new tab page allows you to filter your feed based on tags and sources.

Daily 2.0 - Source for Busy Developers

You can get it here.

4. Toggl Button: Productivity & Time Tracker

If you're a busy freelancer, if you work remotely, or if you just need to track the time you're spending on a project, then Toggl is for you.

This extension requires you to create an account before you can use it. Once you're logged in it enables quick and easy real time productivity tracking with all the data stored in your Toggl account. It comes with a built-in Pomodoro timer, as well as integrations for a whole host of internet services (such as GitHub, Trello and Slack). One of my favorite features is that it will pop up a notification when you've been idle and the timer was running, allowing you to discard the time.

Toggl Button: Productivity & Time Tracker

Toggl can be downloaded here.

5. Lighthouse

Lighthouse is an open-source, automated tool for improving the performance and quality of your web pages. You can either install it via the Chrome Web Store or, as of Chrome version 60, you can run it directly from the Audits tab of the browser's DevTools (press F12 and select Audits).

Once you have opened Lighthouse, click Generate report and optionally select which audit categories to include. Lighthouse will run the selected audits against the page, and generate a report on how well the page did. From there, you can use the failing audits as indicators of how to improve the page. Each audit also includes links to further reading and potential fixes.

Lighthouse is produced by Google, and presumably uses the same ranking factors as their search engine. This means it can offer you some of the best advice out there on how to optimize your site.

Lighthouse

You can grab it here.

6. OneTab

The post 10 Top Chrome Extensions for Your Web Development Workflow appeared first on SitePoint.

How Analytics Helped Solve a UX Issue

Jun 11, 2019

Description:

How Analytics Helped Solve a UX Issue

UX and analytics make a great team. Your website analytics can give you insights enabling you to learn about your users, track their journeys, and find potential problem areas. You can use the quantitative data to inform your qualitative UX approach. Remember, your analytics tell you what’s happening on your website, while UX techniques such as usability testing will help uncover why things are happening.

There are various ways that Google Analytics can be used to uncover how your users are navigating your website. Within the Pages report you can drill down to see how users are navigating to, and from, a selected page in your website. But the User Flow and Behavior Flow reports give more information on multi-step journeys from your most popular landing pages onwards.

user/behavior flow in google analytics

These reports can be hard to analyze, particularly for large websites, due to the fact that there are unlikely to be a series of clear pathways through your website. You’ll find that there are huge numbers of paths that different users can take, which makes finding insights from these reports quite challenging. However, they can be useful for getting a good top-level overview and showing the most dominant pathways through a site. While they suffer from grouping multiple pages, you can often get a good idea of the most common journeys taken by users.

One example of how I’ve used these reports in the past to inform my UX work has been looking out for pogo sticking.

Pogo Sticking

Pogo sticking describes where users bounce between two pages on a website instead of progressing their journey through the site. It can be a sign of confusion on the users’ part and is unlikely to help you convert those users.

The Nielson/Norman group wrote this guide to pogo sticking, which explains it in more detail. It covers some possible reasons behind pogo sticking behavior, and also gives some potential solutions to these problems.

The post How Analytics Helped Solve a UX Issue appeared first on SitePoint.

SitePoint Premium New Releases: Design, Git, Android, Swift + More

Jun 7, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Exploring Git Workflows

Most of us use version control systems on a daily basis. But even though we may use identical systems, we use them in different ways. In this tutorial, Claudio describes GitFlow, the current workflow used by his team.

Read Exploring Git Workflows.

Beginning Android Programming with Android Studio

This hands-on introduction to creating Android apps shows how to install and get started with Android Studio 2, display notifications, create rich user interfaces, use activities and intents, master views and menus, manage data, work with SMS, and package and publish apps to the Android market.

Read Beginning Android Programming with Android Studio.

A Beginner’s Guide to Deployment with Continuous Integration

This guide tackles an important technique in the processing of automating the deployment process—continuous integration (CI). CI achieves efficiency by removing unnecessary bottlenecks in the deployment process, thereby making the transition from a commit to production smooth and consistent.

Read A Beginner’s Guide to Deployment with Continuous Integration.

Design for Hackers

This book explores principles of beautiful design, covering color theory, medium and form, classical principles and techniques, culture and context, the importance, purpose and constraints of design, fonts, scale and proportion, and even ancient graffiti, Monet, the iPhone, and much more.

Read Design for Hackers.

Swift 4 Protocol-Oriented Programming - Third Edition

Build fast and powerful applications by harnessing the power of protocol-oriented programming in Swift 4. Learn from real-world cases, creating a flexible codebase with protocols and protocol extensions, leveraging the power of generics to create very flexible frameworks.

Read Swift 4 Protocol-Oriented Programming - Third Edition.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Design, Git, Android, Swift + More appeared first on SitePoint.

A Deep Dive into User Research Methods

Jun 6, 2019

Description:

A Deep Dive into User Research Methods

User research plays a crucial role in shaping any successful product or service. It keeps the user at the heart of the experience by tailoring it to their needs, and in turn provides real advantage over competitors. But with a growing arsenal of different research methods out there, it can be a challenge to know which is best to use, and when.

This guide offers an overview of the fundamentals for each of the most commonly used methods, providing direction on when to use them — and more importantly, why.

We’ll cover:

the origins of user research discovery and exploratory research quant and qual, and the difference between them core methodologies: user interviews ethnography and field studies surveys and questionnaires analytics and heatmaps card sorts and tree tests usability studies further reading and resources key takeaways The Origins of User Research

Product designers and engineers have incorporated user feedback into their process for centuries. However, it wasn’t until 1993 that the term “user experience” (UX) was coined by Don Norman during his time at Apple.

As the discipline of UX evolved and matured, practitioners began to use investigative research techniques from other fields, such as science and market research. This enabled decisions to be informed by the end user, rather than the design teams’ assumptions, laying the groundwork for UX research as we know it today.

That’s a quick rundown of the origins. Now let’s dive into some research frameworks.

Discovery and Evaluative Research

User-centered design means working with your users all throughout the project — Don Norman

Broadly speaking, user research is used to either discover what people want and need or evaluate if ideas are effective. The methods to achieve these two distinct outcomes can be loosely divided into two groups.

Strategize: Discovery Research

Methods that help to answer unknowns at the beginning of a project can be referred to as Discovery Research. These methods range from reviewing existing reports, data and analytics to conducting interviews, surveys and ethnographic studies. These methods ensure that you have a solid understanding of who your user is, what they need and the problems they face in order to begin developing a solution.

Execute and Assess: Evaluative Research

Once a clearer picture of the end user and their environment has been established, it’s time to explore possible solutions and test their validity. Usability studies are the most common method employed here. Evaluative research provides you with the knowledge you need to stay focussed on the user and their specific requirements.

Examples

Discovery Research Methods Evaluative Research Methods field study diary study one-to-one interview focus group behavioral analytics review open card sort email survey contextual inquiry remote usability testing closed card sort tree test benchmarking analytics review heatmaps popup poll usability benchmark testing impression testing Quant and Qual, and the Difference Between Them

Although every design problem is different, it’s generally agreed that a combination of both qualitative and quantitative research insights will provide a balanced foundation with which to form a more successful design solution. But what do these pronunciation-averse words mean?

Quantitative (statistical) research techniques involve gathering large quantities of user data to understand what is currently happening. This answers important questions such as “where do people drop off during a payment process”, or “which products were most popular with certain user groups” and “what content is most/least engaging”.

Quantitative research methods are often used to strategize the right direction at the start of a project and assess the performance at the end using numbers or metrics. Common goals include:

comparing two or more products or designs getting benchmarks to compare the future design against calculating expected cost savings from some design changes pie chart of application completion rates — 52.66% completed, 47.34% not completedQuantitative data analysis can offer useful insights such as abandonment points on a form. This can lead to further qualitative studies to understand why.

Qualitative (observational) research techniques involves directly observing small user groups to understand attitudes, behaviors and motivations. This is where we begin to understand why something is happening and how to solve a problem.

You can optimize everything and still fail. That’s where qualitative approaches come in. By asking “why”, we can see the opportunity for something better beyond the bounds of the current best. ― Erika Hall

Qualitative research methods are also used to strategize the right direction at the start of a project, and to inform design decisions throughout the ideation process. Common goals include:

to uncover trends in thoughts and opinions understand a problem more deeply to develop a hypothesis for a quantitative research study Christian Rohrer, pictured giving a talk on  user research methodsChristian Rohrer authored a popular framework for understanding user research methods, illustrating where 20 popular methods appear along three dimensions, including quantitative and qualitative. Source. Core Methodologies

So that’s enough of the background behind the methods. Let’s dive into the methods themselves. It’s worth noting that, since every project is different, there’s no quick way of strictly stating which method is best for what. However, pros and cons have been listed for each.

1. User interviews

Qualitative | Discover/Evaluate

Interviews allow you to ask questions to help see things from the participants’ perspective. They are usually recorded and later analyzed to find out what the beliefs, attitudes and drivers of users are, alongside uncovering new considerations to aid with ideation.

Stories are where the richest insights lie. Your objective is to get to this point in every interview. — Steve Portigal

Interview length, style and structure can vary depending on what you’re trying to achieve, and the access to and availability of participants. The following are some different types of interviews.

One-to-one interviews are often conducted in a lab or coffee shop, but can be undertaken almost anywhere with a little preparation. In-person interviews are preferable to remote (via phone or video) as they offer additional insights through body language. Sessions are conducted with questions that loosely follow a discussion guide. This allows you to uncover new learnings around an objective and not get sidetracked.

smiling woman with postit notes

Focus groups are used to gain a consensus from a group of 3–10 representatives of a target audience when you’re short on time or availabile participants. Focus groups take the form of discussions and exercises and are a good way of assessing what people want from a product or service and their opinions on things. They’re not recommended for evaluating interface usability, due to their lack of focus and the potential for groupthink bias.

Contextual inquiry interviews are the holy grail of interview methods. They’re conducted within the participants’ everyday environment whilst they go about their daily activities. A researcher can observe a participant and discuss what they did, and why, whilst the activities take place. Unlike other interviews, the researcher usually summarizes the findings back to the participant at the end, offering them a chance to give final corrections and clarifications. This method is used to generate highly relevant and reliable insights from real situations, but it can be very time consuming.

For more on user interviews, there’s some great resources on the Interaction Design Foundation website.

2. Field Studies

Qualitative | Discover

Field studies involve observing people as they interact with a product, service, or each other, in their natural working or living environment (rather than in a lab) to better understand user behavior and motivations in context. These studies are usually conducted over longer periods of time than most other methods, recording extensive field notes for later analysis.

Ethnographic research involves researchers actively participating within a group setting, becoming the subject themselves. This method is particularly useful when studying a target audience that is culturally or socially different from your own, and it can uncover lots of unknowns and important considerations.

Direct observation involves passively observing from a distance (like a curious fly on a wall), allowing researchers to uncover problems and workarounds in user journeys and flows (such as retail store layouts), and also allowing for future improvements.

a line of people glued to their mobile phones

User logs involve diary studies and video journals, and are sometimes referred to as the “poor man’s field study”. They allow the user to generate the data for you by recording their experiences with the focus of the study at a specific time each day over a period of time. The real-time insights provided can be useful for understanding long-term behaviors such as habits, workflows, attitudes, motivations, or changes in behavior.

The post A Deep Dive into User Research Methods appeared first on SitePoint.

How to Replace Redux with React Hooks and the Context API

Jun 5, 2019

Description:

The most popular way for handling shared application state in React is using a framework such as Redux. Quite recently, the React team introduced several new features which include React Hooks and the Context API. These two features effectively eliminated a lot of challenges that developers of large React projects have been facing. One of the biggest problems was 'prop drilling' which was common with nested components. The solution was to use a state management library like Redux. This unfortunately came with the expense of writing boilerplate code — but now, it's possible to replace Redux with React Hooks and the Context API.

In this article, you are going to learn a new way of handling state in your React projects without writing excessive code or installing a bunch of libraries as is the case with Redux. React hooks allows you to use local state inside of function components, while the Context API allows you to share state with other components.

Prerequisites

In order to follow along with this tutorial, you will need to have a good foundation in the following topics:

Getting Started with React React Hooks Foundation in Redux

The technique you will learn here is based on patterns that were introduced in Redux. This means you need to have a firm understanding of reducers and actions before proceeding. I am currently using Visual Studio Code, which seems to be the most popular code editor right now (especially for JavaScript developers). If you are on Windows, I would recommend you install Git Bash. Use the Git Bash terminal to perform all commands provided in this tutorial. Cmder is also a good terminal capable of executing most Linux commands on Windows.

You can access the complete project used in this tutorial from this GitHub Repository.

The post How to Replace Redux with React Hooks and the Context API appeared first on SitePoint.

UI Code Challenge #1 – Heartbeats

Jun 5, 2019

Description:

Do you ever find that the UI screens that we see in blockbuster movies, television, and games are so much more fun than the UIs we might build at work? Here's your chance to code something fun and maybe even win an Amazon Gift Card.

The post UI Code Challenge #1 – Heartbeats appeared first on SitePoint.

Content as UX: Building a More Human Web

Jun 4, 2019

Description:

Content as UX: Building a More Human Web

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

How are you enjoying this article so far? Whatever your feelings, I’ll bet you’ll agree that content is a vital part of the user experience.

Wait. Did I say “a vital part”? I meant “the critical part”. After all, every user journey, whatever its goal, ultimately involves a user getting to content, or adding their own. That content may be text, like this article, or it may be imagery, video, audio — you name it. But whatever it is, it’s the point of the user’s interaction with every site or product.

Yet traditionally (and all too often still) when we design websites or make products, we design visually, and the content spaces are left blank. If you’re doing things as most do, you’re probably going to show the wireframes or mockups to someone internal — maybe even your founder — and ask them to fill the spaces.

Ugh. At least, that’s what your colleague is probably thinking at this point. Now they have the burden and responsibility of filling the literal and metaphorical blank page — but a blank page that already has a goal or direction they’ve had no part in choosing.

Here I’m going to suggest an alternative way to consider content, where content is UX.

1. How Can Content Be UX?

I said above that content is the critical part of the UX. Let’s build on that now.

Content is user experience.

Look at a site like YouTube. The landing page is a list of content. Even better, that content is presented based on your (or my) past usage patterns. The data associated with that content — the image, title, name of the account that uploaded the media, total views and upload date — is also content. When you access a video, the comments beneath it are content.

Text beneath video is content

It’s all content. Content is the user experience. It’s what we’re here to use.

Okay, you say, but it’s YouTube. My product isn’t content.

Fine, let’s consider the example of a new computer. I just had to replace mine after six years of trusty service. I got a MacBook Air, and it came in a lovely box. Nice user experience. Other than the actual computer, there’s not much content here, right?

Not much content on the MacBook Air box

Well, no. But then I open the box, plug the thing in, and notice these little leaflets tucked away.

Leaflets inside the MacBook Air box

I’ve included the matchbox for a size comparison. I wear glasses, but I felt like I needed a magnifying glass to read the leaflet titled MacBook Air Info. In fact, I only read the first sentence (which hurt my eyes):

Review the Macbook Air Essentials guide before using MacBook Air.

“Right you are, Apple,” I thought.

But what’s this? The only other leaflet in the box is a MacBook Air Quick Start Guide. Is … is that what they meant? I hope so, because it has slightly bigger text, and it was the only other thing I glanced through before I turned on my thrilling new purchase.

Question: how am I ever going to start creating glorious content on that device, or access the glorious content accessible on the Web, if I can’t read the instruction content to get said device going? If I don’t need the content to get it work, then why include these crazy-tiny, unreadable leaflets with the product in the first place?

This experience doesn’t exactly fill me with confidence, nor the idea that Apple cares about actual people. Sure, the packaging is nice. But right now it feels like the business is in love with its own products more than its users.

Bottom line: content is user experience. Even in the Real World™.

The post Content as UX: Building a More Human Web appeared first on SitePoint.

SitePoint Premium New Releases: Docker, Phoenix, VS Code + More

May 31, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Phoenix Web Development

Learn functional programming through building a high-performance functional prototype of a web app from scratch using Elixir and Phoenix. Understand the Elixir Concurrency and parallelization model to build blazingly fast apps. Test, debug and deploy your web apps using the Phoenix framework.

Read Phoenix Web Development.

Debugging with Visual Studio Code: An Introduction

Learn to use Visual Studio Code's built-in debugging features which permit easier debugging and variable monitoring. Discover how you can improve your debugging experience!

Read Debugging with Visual Studio Code: An Introduction.

Docker Cookbook Second Edition

Docker is an open source platform for building, shipping, managing, and securing containers. This book includes practical exmaples showing you how to manage containers efficiently; how to integrate with orchestration tools such as Kubernetes; and best practices on improving the efficiency and security of containers.

Read Docker Cookbook Second Edition.

Beginning ASP.NET 4.5.1 in C# and VB

This book covers how to get started with ASP.NET 4.5.1; how to overcome common HTML and CSS formatting problems; techniques for managing server controls; creating consistent page layouts; the ASP.NET state engine; modifying SQL data; and also jQuery, LINQ, the Entity Framework, and security.

Read Beginning ASP.NET 4.5.1 in C# and VB.

A Pocket Guide to HTML Email

Creating HTML emails is often thought of as an unpleasant and neglected part of web design, but email is hugely important for reaching out to your users, customers and clients. In this book, Andy shows you how to design and build responsive email your customers and clients will love to receive.

Read A Pocket Guide to HTML Email.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Docker, Phoenix, VS Code + More appeared first on SitePoint.

Introduction to Vue.js and the Quasar Framework

May 30, 2019

Description:

Introduction to Vue.js and the Quasar Framework

In recent years, we’ve seen a proliferation of JavaScript tools and frameworks, such as Angular and React. I remember when I bought a book about Grunt.js: it was already being dropped by developers, who had started using other tools like Gulp, “the streaming build system”. But anyone who jumped on that train was likely to switch again really fast, because webpack came along and replaced them all.

But among JavaScript frameworks, one has seen particularly rapid growth in recent years: Vue.js. It’s been so popular that its rate of growth has become explosive compared to others in this space.

Vue has become one of the primary contenders due its soft learning curve. It lends itself nicely to gradual implementation. It has a modular, component-based architecture. And it has wide usage and a developed ecosystem of tools. If you’re interested in getting started with Vue, you can check out our book Jump Start Vue.js to start getting on your way to using Vue in your projects.

Vue Tools, Terminology and Landscape

As with most technologies one ventures to master, getting to grips with Vue includes getting to know the terms and concepts, and getting comfortable with its ecosystem of tools and building blocks.

Vue Router is an indispensable part of all Vue single-page applications. It provides navigation control, nested routing, route-view mapping, and many other features.

Vuex is a “state management pattern + library” for Vue apps. It’s like a centralized data store helping us to manage state in our applications, across all components. Handling stage across multiple parts of front-end applications can quickly get out of hand, and thus the need for a comprehensive solution. We talk more about Vuex in our Vuex Beginners Guide.

Vue devtools can make life easier for developers. It helps you keep track of the components, state, and events in our applications. You can find more about this tool in Chapter 2 of our book dedicated to Vue tools.

Vue Cli provides a command-line toolset for building Vue applications — prototyping, fast scaffolding of JavaScript applications with included CSS pre-processors, ESLint, Babel, Typescript support, PWA support, and so on. Vue CLI — especially in its latest incarnation — is a game changer, and presents a little ecosystem of its own. The Vue CLI 3 plugin for building Electron applications is one very good example. We also devoted a whole book to it, the Beginner’s Guide to Vue CLI, so you can dive right in.

Vue Component System is another one of Vue’s strengths. It enables us to modularize our applications, to encapsulate pieces of markup, logic and styling and reuse them.

Vue Cli Plugin Component, by David Desmaisons, helps with development of components to be published on npm.

If you’re looking for a deep dive into these and other Vue.js tools, I recommend you take a look through Vue.js: Tools & Skills.

Awesome Vue is also an excellent resource. It’s an in-depth, categorized, up-to-date collection/repo of all the pieces of the Vue ecosystem and Vue.js resources.

Quasar, the Vue framework we’re covering here, also has Awesome Quasar, an excellent repo page with many useful resources.

Quasar

Vue is a JavaScript framework for building user interfaces. On its own, however, it doesn’t provide actual UI elements, or components, or consistent designs we can use. That’s why, on top of Vue, many UI frameworks have been built, to provide users with reusable, styled components. We can think of it like different takes on Twitter’s Bootstrap — only for Vue.

If you’re interested in finding out more, I recommend taking a look at “Five Vue UI Libraries for Your Next Project”, which is Chapter 3 of Vue.js: Tools & Skills. One serious contender in this space, which we didn’t cover, is Vuetify, a material design component framework with quite a big following. Another one is Quasar.

Quasar is a high performance, Material Design 2, full front-end stack for Vue.js.

It’s an MIT-licensed, simple-to-use but powerful UI kit that supplements Vue.js to provide a full-featured toolset for building responsive front-end apps without having to delve too deep into the scaffolding and configuration.

A page from the Quasar docs

As we can see in the Quasar docs, it comes with a lot of UI components, and layout elements and helpers.

It gives us three ways to bootstrap our app:

UMD / Standalone makes it possible to start small, by including scripts and styles we need from a CDN. This method doesn’t rely on VUE CLI or the building of assets. Quasar CLI claims to be “the pride of the Quasar framework”, and is the recommended way of building Quasar applications. It can be used to build: SPAs (single-page apps/websites) SSRs (server-side rendered apps/websites) PWAs (progressive web apps) mobile apps (through Cordova) Electron apps Vue CLI 3 plugin

We’ll follow Quasar team’s recommendation and use Quasar CLI.

Bootstrapping a Quasar App with Quasar CLI

Terminal readout of installed Node and npm versions

Before we install Quasar CLI, we need to make sure we have the right versions of node (>= 8 at the time of writing) and npm (>= 5). If not, we need to either install or update it. Then we can install Quasar CLI:

sudo npm install -g @quasar/cli

Terminal view of Quasar being installed

Now we can use it to bootstrap our projects. Quasar has a thorough documentation on Quasar CLI. We’ll skim through it and discuss most relevant parts.

The command we use is quasar + subcommand. Just quasar will list the commands for us, and quasar <command> --help will get us the help for the given subcommand.

We use quasar create to scaffold a quasar project.

Using Quasar help in the terminal

We’re then presented with a list of choices about the project we want to bootstrap.

Running quasar create in the terminal

After the project is scaffolded, we can cd into the directory and start a development server with quasar dev. The project is built and the browser will open the provisional index page on localhost.

Our provisional index page

Note: for production, once our project is done, we’d be using quasar build to compile our resources.

The dev server provides us with Hot Reload, which preserves the state in the browser through reloads.

Hot Reload is much more than just refreshing your browser when the code changes. It skips the refresh and updates your code on the fly, while maintaining your app’s state (like your Vue’s model data).

As we write code and save our files/Vue components, along with a page reload in the browser, the terminal shell in which we started the dev server will output many errors in the code. This section in Vue.js: Tools & Skills gives a pretty good explanation of why.

Once we’ve bootstrapped our project, we get this directory structure (with the exclusion of node_modules):

The post Introduction to Vue.js and the Quasar Framework appeared first on SitePoint.

How to Build a Chrome Extension with Vue

May 29, 2019

Description:

Browser extensions are small programs that can modify and enhance the functionality of a web browser. They can be used for a variety of tasks, such as blocking ads, managing passwords, organizing tabs, altering the look and behavior of web pages, and much more.

The good news is that browser extensions aren’t difficult to write. They can be created using the web technologies you’re already familiar with — HTML, CSS and JavaScript — just like a regular web page. However, unlike regular web pages, extensions have access to a number of browser-specific APIs, and this is where the fun begins.

In this tutorial, I’m going to show you how to build a simple extension for Chrome, which alters the behavior of the new tab page. For the JavaScript part of the extension, I’ll be using the Vue.js framework, as it will allow us to get up and running quickly and is a lot of fun to work with.

The code for this tutorial can be found on GitHub.

The Basics of a Chrome Extension

The core part of any Chrome extension is a manifest file and a background script. The manifest file is in a JSON format and provides important information about an extension, such as its version, resources, or the permissions it requires. A background script allows the extension to react to specific browser events, such as the creation of a new tab.

To demonstrate these concepts, let’s start by writing a “Hello, World!” Chrome extension.

Make a new folder called hello-world-chrome and two files: manifest.json and background.js:

mkdir hello-world-chrome cd hello-world-chrome touch manifest.json background.js

Open up manifest.json and add the following code:

{ "name": "Hello World Extension", "version": "0.0.1", "manifest_version": 2, "background": { "scripts": ["background.js"], "persistent": false } }

The name, version and manifest_version are all required fields. The name and version fields can be whatever you want; the manifest version should be set to 2 (as of Chrome 18).

The background key allows us to register a background script, listed in an array after the scripts key. The persistent key should be set to false unless the extension uses chrome.webRequest API to block or modify network requests.

Now let’s add the following code to background.js to make the browser say hello when the extension is installed:

chrome.runtime.onInstalled.addListener(() => { alert('Hello, World!'); });

Finally, let’s install the extension. Open Chrome and enter chrome://extensions/ in the address bar. You should see a page displaying the extensions you’ve installed.

As we want to install our extension from a file (and not the Chrome Web Store) we need to activate Developer mode using the toggle in the top right-hand corner of the page. This should add an extra menu bar with the option Load unpacked. Click this button and select the hello-world-chrome folder you created previously. Click Open and you should see the extension installed and a “Hello, World!” popup appear.

Hello World Extension

Congratulations! You just made a Chrome extension.

Overriding Chrome’s New Tab Page

The next step will to have our extension greet us when we open up a new tab. We can do this by making use of the Override Pages API.

Note: before you progress, please make sure to disable any other extensions which override Chrome’s new tab page. Only one extension at a time may alter this behavior.

We’ll start off by creating a page to display instead of the new tab page. Let’s call it tab.html. This should reside in the same folder as your manifest file and background script:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My New Tab Page!</title> </head> <body> <h1>My New Tab Page!</h1> <p>You can put any content here you like</p> </body> </html>

Next we need to tell the extension about this page. We can do so by specifying a chrome_url_overrides key in our manifest file, like so:

"chrome_url_overrides": { "newtab": "tab.html" }

Finally, you need to reload the extension for the changes to take effect. You can do this by clicking the reload icon for the Hello World extension on Chrome’s extensions page.

Reload the extension

Now, when you open a new tab, you should be greeted by your custom message.

Adding Vue to the Extension

Now we have a very basic implementation of our extension up and running, the time has come to think about what the rest of the desired functionality will look like. When a user opens a new tab, I would like the extension to:

Fetch a joke from the wonderful icanhazdadjoke.com. Display that joke in a nicely formatted manner to the user. Display a button for the user to favorite the joke. This will save the joke to chrome.storage. Display a button for the user to list favorited jokes.

You could, of course, do all of this with plain JavaScript, or a library like jQuery — and if that’s your thing, feel free!

For the purposes of this tutorial, however, I’m going to implement this functionality using Vue and the awesome vue-web-extension boilerplate.

Using Vue allows me to write better, more organized code faster. And as we’ll see, the boilerplate provides several scripts that take the pain out of some of the common tasks when building a Chrome extension (such as having to reload the extension whenever you make changes).

vue-web-extension-boilerplate

This section assumes that you have Node and npm installed on your computer. If this isn’t the case, you can either head to the project’s home page and grab the relevant binaries for your system, or you can use a version manager. I would recommend using a version manager.

We’ll also need Vue CLI installed and the @vue/cli-init package:

npm install -g @vue/cli npm install -g @vue/cli-init

With that done, let’s grab a copy of the boilerplate:

vue init kocal/vue-web-extension new-tab-page

This will open a wizard which asks you a bunch of questions. To keep this tutorial focused, I answered as follows:

? Project name new-tab-page ? Project description A Vue.js web extension ? Author James Hibbard <jim@example.com> ? License MIT ? Use Mozilla's web-extension polyfill? No ? Provide an options page? No ? Install vue-router? No ? Install vuex? No ? Install axios? Yes ? Install ESLint? No ? Install Prettier? No ? Automatically install dependencies? npm

You can adapt your answers to suit your preferences, but the main thing to be certain of is that you choose to install axios. We’ll be using this to fetch the jokes.

Next, change into the project directory and install the dependencies:

cd new-tab-page npm install

And then we can build our new extension using one of the scripts the boilerplate provides:

npm run watch:dev

This will build the extension into a dist folder in the project root for development and watch for changes.

To add the extension to Chrome, go through the same process as outlined above, making sure to select the dist folder as the extension directory. If all goes according to plan, you should see a “Hello world!” message when the extension initializes.

Project Setup

Let’s take a minute to look around our new project and see what the boilerplate has given us. The current folder structure should look like this:

. ├── dist │ └── <the built extension> ├── node_modules │ └── <one or two files and folders> ├── package.json ├── package-lock.json ├── scripts │ ├── build-zip.js │ └── remove-evals.js ├── src │ ├── background.js │ ├── icons │ │ ├── icon_128.png │ │ ├── icon_48.png │ │ └── icon.xcf │ ├── manifest.json │ └── popup │ ├── App.vue │ ├── popup.html │ └── popup.js └── webpack.config.js

As you can see, from the config file in the project root, the boilerplate is using webpack under the hood. This is awesome, as this gives us Hot Module Reloading for our background script.

The src folder contains all of the files we’ll be using for the extension. The manifest file and background.js should be familiar, but also notice a popup folder containing a Vue component. When the boilerplate builds the extension into the dist folder, it will pipe any .vue files through the vue-loader and output a JavaScript bundle which the browser can understand.

Also in the src folder is an icons folder. If you look in Chrome’s toolbar, you should see a new icon for our extension (also known as the browser action). This is being pulled from this folder. If you click it, you should see a popup open which displays “Hello world!” This is created by popup/App.vue.

Finally, note a scripts folder containing two scripts — one to remove eval usages to comply with the Content Security Policy of Chrome Web Store and one to package your extension into a .zip file, which is necessary when uploading it to the Chrome Web Store.

There are also various scripts declared in the package.json file. We’ll be using npm run watch:dev for developing the extension and later on npm run build-zip to generate a ZIP file to upload to the Chrome Web Store.

The post How to Build a Chrome Extension with Vue appeared first on SitePoint.

Build a Desktop Application with Electron and Angular

May 28, 2019

Description:

In this tutorial we’ll build a cross-platform desktop application with Electron and web technologies such as TypeScript and Angular. Electron.js is a popular platform for building cross-platform desktop apps for Windows, Linux and macOS with JavaScript, HTML, and CSS. It’s created and maintained by GitHub and it’s available under the MIT permissive license. It was […]

The post Build a Desktop Application with Electron and Angular appeared first on SitePoint.

Non-relational Databases and Supporting Mixed Workloads

May 28, 2019

Description:

This article was created in partnership with MongoDB. Thank you for supporting the partners who make SitePoint possible.

Suppose that you’re building an e-commerce platform and as part of the exercise, you need to come up with a new data architecture for inventory management. You need to support fast, transactional workloads to actually keep track of inventory in near real-time.

The business would also like to be able to answer questions such as "based on historical data, when should we restock on widgets and gizmos?" and “who are the people that are buying widgets and generally, where are they located?” Your data architecture needs to support mixed workloads.

Where would you start?

The post Non-relational Databases and Supporting Mixed Workloads appeared first on SitePoint.

SitePoint Premium New Releases: Webpack, TensorFlow, Swift & Parcel

May 24, 2019

Description:

We’re working hard to keep you on the cutting edge of your field with SitePoint Premium. We’ve got plenty of new books to check out in the library — let us introduce you to them. A Beginner’s Guide to Webpack When using JavaScript module bundler webpack for the first time, it can be difficult to […]

The post SitePoint Premium New Releases: Webpack, TensorFlow, Swift & Parcel appeared first on SitePoint.

A Beginner’s Guide to Webpack

May 22, 2019

Description:

A Beginner’s Guide to Webpack

Nowadays, we’re forced to use many accessory tools to facilitate, speed up and optimize our web development workflow. Often though, such tools add an extra layer of complexity into the stack. As a result, we need to utilize additional time and effort to learn, understand and use these tools correctly. The same is true for webpack.

When using webpack for the first time, it can be difficult to understand how it works and how it should be used. Although it has good documentation, it can be daunting for novices, and it has a steep learning curve. However, webpack is worth learning and can save considerable time and effort in the long run. In this tutorial, I’ll introduce all the core concepts to help you get started.

Note: in this tutorial I’ve used webpack 4.30.

What Is Webpack?

As its core, webpack is a static module bundler. In a particular project, webpack treats all files and assets as modules. Under the hood, it relies on a dependency graph. A dependency graph describes how modules relate to each other using the references (require and import statements) between files. In this way, webpack statically traverses all modules to build the graph, and uses it to generate a single bundle (or several bundles) — a JavaScript file containing the code from all modules combined in the correct order. “Statically” means that, when webpack builds its dependency graph, it doesn’t execute the source code but stitches modules and their dependencies together into a bundle. This can then be included in your HTML files.

Now, to expand the above cursory overview, let’s explore the main concepts webpack uses.

Webpack Main Concepts

Webpack has some main concepts which we need to understand clearly before digging in its practical implementation. Let’s examine them one by one:

Entry. The entry point is the module, which webpack uses to start building its internal dependency graph. From there, it determines which other modules and libraries that entry point depends on (directly and indirectly) and includes them in the graph until no dependency is left. By default, the entry property is set to ./src/index.js, but we can specify a different module (or even multiple modules) in the webpack configuration file.

Output. The output property instructs webpack where to emit the bundle(s) and what name to use for that file(s). The default value for this property is ./dist/main.js for the main bundle and ./dist for other generated files — such as images, for example. Of course, we can specify different values in the configuration depending on our needs.

Loaders. By default, webpack only understands JavaScript and JSON files. To process other types of files and convert them into valid modules, webpack uses loaders. Loaders transform the source code of non-JavaScript modules, allowing us to preprocess those files before they’re added to the dependency graph. For example, a loader can transform files from a CoffeeScript language to JavaScript or inline images to data URLs. With loaders we can even import CSS files directly from our JavaScript modules.

Plugins. Plugins are used for any other task that loaders can’t do. They provide us with a wide range of solutions about asset management, bundle minimization and optimization, and so on.

Mode. Typically, when we develop our application we work with two types of source code — one for the development build and one for the production build. Webpack allows us to set which one we want to be produced by changing the mode parameter to development, production or none. This allows webpack to use built-in optimizations corresponding to each environment. The default value is production. The none mode means that there won’t be used any default optimization options. To learn more about the options webpack uses in development and production mode, visit the mode configuration page.

How Webpack Works

In this section we’ll examine how webpack works. Even a simple project contains HTML, CSS and JavaScript files. Also, it can contains assets such as fonts, images, and so on. So, a typical webpack workflow would include setting up an index.html file with the appropriate CSS and JS links, and the necessary assets. Also, if you have many CSS and JS modules which depend on each other, they need to be optimized and properly combined in one unit ready for production.

To do all this, webpack relies on configuration. Although webpack 4 comes with reasonable defaults, for any non-trivial project you’ll need to provide a special configuration file webpack.config.js, which describes how the files and assets should be transformed and what kind of output should be generated. This file can quickly become quite monolithic, which makes it hard to understand how webpack does its job unless you know the main concepts behind its working.

Based on the provided configuration, webpack starts from the entry points and resolves each module it encounters while constructing the dependency graph. If a module contains dependencies, the process is performed recursively against each dependency until the traversal has completed. Then webpack bundles all project’s modules into a small number of bundles — usually, just one — to be loaded by the browser.

Getting Started

Note: you can find the files for our project in the GitHub repo.

Now that we have solid theoretical foundation, let’s implement it in practice.

To start, we’ll create a new directory and switch to it. Then we’ll initialize a new project:

mkdir learn-webpack cd learn-webpack npm init -y

Next, we need to install webpack and webpack CLI locally:

npm install webpack webpack-cli --save-dev

Now, the content of the generated package.json should be similar to the following:

{ "name": "learn_webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.30.0", "webpack-cli": "^3.3.0" } }

Besides bundling modules, webpack can be used as a simple task runner. We can create webpack tasks by including the name of our task followed by its instructions in the scripts section of the package,json file. Let’s try this now. Open package.json and change the scripts object to the following:

"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode development", "build": "webpack --mode production" },

Within the scripts property, webpack allows us to reference locally installed npm packages by their names. We use that and the --mode flag to define dev and build tasks, which will run webpack in development (npm run dev) and production (npm run build) mode respectively.

Before we test the tasks we’ve just created, let’s create a src directory and put an index.js file in it so that it contains console.log("Hello webpack");. Now we can already to run the dev task to start webpack in development mode:

$ npm run dev > learn_webpack@1.0.0 dev C:\Users\User\Webpack\learn_webpack > webpack --mode development Hash: 5bb3bdc1efd7b7f4b627 Version: webpack 4.30.0 Time: 226ms Built at: 2019-04-16 17:48:32 Asset Size Chunks Chunk Names main.js 3.8 KiB main [emitted] main Entrypoint main = main.js [./src/index.js] 27 bytes {main} [built]

Great! It works as expected. But to verify that we get the correct output, we need to display the result in the browser. To do that, let’s create an index.html file in the dist directory:

<!doctype html> <html> <head> <title>Getting Started</title> </head> <body> <script src="main.js"></script> </body> </html>

Now, if we open the file in the browser, we should see the Hello webpack message in the console.

So far, so good. But writing our index.html file manually can be problematic in some cases. For example, if we change the name of our entry point, the generated bundle will be renamed, but our index.html file will still reference the old name. So, we’ll need to update our HTML file manually every time we rename an entry point or add new one. Fortunately, we can easily fix that with the html-webpack-plugin. Let’s install it now:

npm install html-webpack-plugin --save-dev

At this point, to activate the plugin, we need to create a webpack.config.js file in the root directory with the following content:

const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { plugins: [ new HtmlWebpackPlugin({ title: "Webpack Output", }), ], };

As you can see, to activate a webpack plugin, we need to include it and then add it to the plugins array. If needed, we also pass options to the plugin.

Let’s run our build now to see what will happen:

$ npm run build > learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack > webpack --mode production Hash: e56a796f5ccfebcc8270 Version: webpack 4.30.0 Time: 1088ms Built at: 2019-04-16 20:44:47 Asset Size Chunks Chunk Names index.html 183 bytes [emitted] main.js 956 bytes 0 [emitted] main Entrypoint main = main.js [0] ./src/index.js 27 bytes {0} [built] Child html-webpack-plugin for "index.html": 1 asset Entrypoint undefined = index.html [2] (webpack)/buildin/global.js 472 bytes {0} [built] [3] (webpack)/buildin/module.js 497 bytes {0} [built] + 2 hidden modules

Let’s open the index.html. As we can see, the plugin automatically creates an updated index.html file for us which uses the title option from the configuration:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Webpack Output</title> </head> <body> <script type="text/javascript" src="main.js"></script></body> </html>

Let’s now expand our project and specify custom names for the entry and output properties. In webpack.config.js we add the following before the plugins property:

entry: './src/app.js', output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') },

Now, we’ll create an src/component.js file:

export default (text = "Hello webpack") => { const element = document.createElement("p"); element.innerHTML = text; return element; };

Next, we rename index.js to app.js to reflect our changes, and swap its content with the following:

import component from "./component"; document.body.appendChild(component());

Now, let’s run webpack in production mode:

$ npm run build > learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack > webpack --mode production Hash: 9f78936f8a2a21061f0b Version: webpack 4.30.0 Time: 1689ms Built at: 2019-04-17 23:43:40 Asset Size Chunks Chunk Names index.html 190 bytes [emitted] main.bundle.js 1.04 KiB 0 [emitted] main Entrypoint main = main.bundle.js [0] ./src/app.js + 1 modules 227 bytes {0} [built] | ./src/app.js 79 bytes [built] | ./src/component.js 148 bytes [built] Child html-webpack-plugin for "index.html": 1 asset Entrypoint undefined = index.html [2] (webpack)/buildin/global.js 472 bytes {0} [built] [3] (webpack)/buildin/module.js 497 bytes {0} [built] + 2 hidden modules

Let’s examine and clarify the information from the webpack output. Beginning from the top, we see the hash of the build, webpack version, and the time it took to execute the build. Next, we see the files generated in the dist directory (index.html and main.bundle.js). Below them, we see the entry module (app.js) and its dependency (component.js). The output after Child html-webpack-plugin for "index.html": is related to the internal work of the html-webpack-plugin and we can safely ignore it.

So now, in the dist folder, we have the newly generated bundle file main.bundle.js. If we open index.html in the browser, we should see Hello webpack displayed on the page. Also, if we check the source of index.html, we’ll see that the value of the src property in the script tag is updated to main.bundle.js.

The post A Beginner’s Guide to Webpack appeared first on SitePoint.

Why the Highest Paid Developers “Fight” Their Coworkers

May 21, 2019

Description:

You're going to be asked to do it.

At some point, if it hasn't happened already, your coworkers or your boss will ask you to do something foolish. Something you know will make things worse for you, your coworkers, maybe even the business itself.

If you're like most developers, you do it anyway.

That's what most will do, right? It's better to keep your head down, avoid making waves and simply do what you're told. Job security isn't a thing anymore, but that's one of the best things you can do to keep your job, for a while at least.

This Common Mistake Creates a Career Handicap

This is the problem.

Most employees want to keep their jobs and their clients. They don't have the leverage or control they want over their own careers. They need their job. In fact, most people are terrified of losing their jobs.

This has a cascading effect.

Research shows the fear of losing your job creates job dissatisfaction and a lack of commitment at work. This, in turn, affects job performance, negatively increasing the likelihood that you will lose your job. It's a vicious cycle that seems to repeat itself over and over.

But there's something worse than the fear of a job loss.

It's the misplaced confidence or expectation of job security, the kind of confidence that crushes you when you're actually let go. Both of these issues are a problem, and both of these issues are continually ignored.

Why is it a problem?

Because 78 percent of employees live paycheque-to-paycheque. This includes workers making $100,000+ per year. This is the real reason why most employees have no leverage, no ability to say no. This is the reason most developers won't fight with their coworkers.

Why Developers Need to Fight Their Coworkers

What do I mean by "fight?"

The post Why the Highest Paid Developers “Fight” Their Coworkers appeared first on SitePoint.

SitePoint Premium New Releases: Flask, Pug, ECMAScript, Linux + More

May 17, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Mastering Flask Web Development Second Edition

Build modern, secure, production-ready web MVC apps and APIs using Python’s Flask framework. Utilize various extensions like Flask-JWT and Flask-SQLAlchemy to develop powerful applications. Deploy a Flask app on real-world platforms like AWS and Heroku on VMs or Docker containers.

Read Mastering Flask Web Development Second Edition.

React Native Blueprints

Develop real-world Android and iOS apps with React Native, building fun projects from scratch while discovering more efficient techniques. Learn to build professional Android and iOS apps with your JS skills. Use Isomorphic principles to build mobile apps that offer a native user experience.

Read React Native Blueprints.

A Beginner’s Guide to Pug

In this guide, we’ll demonstrate how to get up and running with Pug, a template engine for Node and for the browser. We’ll start by installing it, go over its basic syntax and then look at several examples of using JavaScript in Pug. Finally, we’ll explore a couple of Pug’s more advanced features.

Read A Beginner’s Guide to Pug.

ECMAScript Cookbook

Become a better web programmer by writing efficient and modular code using ES6 and ES8. Learn to write asynchronous code and improve app readability. Explore advanced concepts such as closures, generators and Promises. Use design patterns to create structures to solve common issues.

Read ECMAScript Cookbook.

Linux Essentials, 2nd Edition

Perfect for beginners, Linux Essentials Exam students, and those seeking a career in IT, this book presents task-based lessons on the basics of Linux, including distributions, types of apps, freeware, licensing, operations, navigation, command functions, user types, users and groups, and much more.

Read Linux Essentials, 2nd Edition.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our library for a spin.

The post SitePoint Premium New Releases: Flask, Pug, ECMAScript, Linux + More appeared first on SitePoint.

How to Launch a Side Project from Zero

May 17, 2019

Description:

Since 2017, I have launched several projects including Spider, Pretzel, Stitches and Dribbble color palette.

At first, it wasn't clear which steps of the launch process were more important than others. But after my third launch, I had hatched a plan and started tweaking it. In this article, I will share the lessons I learned and walk you through the process of making a product. Hopefully you can take this as a starting point or inspiration, and make something tailored for yourself.

Start by checking out this checklist that I've developed over a number of side projects. Feel free to run with it and adapt it for your own projects.

https://twitter.com/hyper_yolo/status/1116683418425683968

1. Keep a Problem Notebook

book_of_grudges

Many of us keep an idea notebook, but I would advocate keeping a “book of grudges”: one with problems and wrongs you find intriguing to solve. Mine is a kanban board with different labels — design, social, security, etc. With these labels, I know what problem could be easily solved with a post-it note, and what could be solved by a clever app. I stare at this board often and maintain it diligently — it tells me what my current priority is, and what the next long term goal is.

2. Know Yourself First

If you’re like me, your book of grudges is extensive. To figure out what is worth spending time on, let’s start with why. Why do you want to create a product?

For me, there are two reasons:

I like helping people and listening to their daily struggles. It gives me different perspectives on life. Nothing brings me as much joy as making things. The satisfaction of creating something of my own is far greater than any shiny new job or huge paycheque.

With the two causes combined, I noticed I’m drawn to smaller and refined issues. You can spot a trend among all the products I've made — they are utilitarian and focused.

So, ask yourself why to narrow the field of selections. If new technologies and the possibilities they bring fascinate you, maybe an open-ended, AR powered camera app would excite you. Whatever you choose, starting by understanding your cause will help you feel less overwhelmed.

3. Ideation and Design

Once you have a problem to tackle and you’re armed with enough knowledge regarding the problem, it’s time to ideate the solution. During ideation, the only goal is to generate as many solutions as possible without being judgmental. I write my ideas out in a Markdown file and keep the session around 30 minutes.

The post How to Launch a Side Project from Zero appeared first on SitePoint.

A Beginner’s Guide to Pug

May 16, 2019

Description:

A Beginner’s Guide to Pug

SitePoint Premium gives you an entire collection of books covering developer essentials like Pug, Gulp, Git and more. Join now.

As web designers or developers, we likely all have to write our fair share of HTML. And while this is not the most difficult task, it can often feel a little boring or repetitive. HTML is also static, which means that if you want to display dynamic data (fetched from an API, for example), you invariably end up with a mishmash of HTML stings inside JavaScript. This can be a nightmare to debug and to maintain.

This is where Pug comes in. Pug is a template engine for Node and for the browser. It compiles to HTML and has a simplified syntax, which can make you more productive and your code more readable. Pug makes it easy both to write reusable HTML, as well as to render data pulled from a database or API.

In this guide, I’ll demonstrate how to get up and running with Pug. We’ll start by installing it from npm, go over its basic syntax and then look at several examples of using JavaScript in Pug. Finally, we’ll explore a couple of Pug’s more advanced features by building a simple Node/Express project which uses Pug as its template engine.

What’s a Template Engine and Why Do I Need One?

Before we start looking at Pug, let’s take a second to understand the concepts involved.

A template engine is a program which is responsible for compiling a template (that can be written using any one of a number of languages) into HTML. The template engine will normally receive data from an external source, which it will inject into the template it’s compiling. This is illustrated by the following diagram.

Credit: Dreftymac, TempEngWeb016, CC BY-SA 3.0

This approach allows you to reuse static web page elements, while defining dynamic elements based on your data. It also facilitates a separation of concerns, keeping your application logic isolated from your display logic.

You’re more likely to benefit from a template engine if your site or web application is data driven — such as a staff directory for administering employees, a web store that lists various products for users to buy, or a site with dynamic search functionality.

You won’t need a template engine if you’re fetching a small amount of data from an API (in which case you can just use JavaScript’s native template strings), or if you’re making a small static site.

A Little History

It’s also worth noting that Pug used to be called Jade until it was forced to change its name due to a trademark claim in 2015. The name change took effect with version 2.0.

There’s still a lot of Jade-related material available online. And while some of it’s probably still quite valid, the fact that the name change coincided with a major version bump means that Pug’s syntax has several differences, deprecations, and removals compared to its predecessor. These are documented here.

If you’re interested in finding out more, you can read the original name change announcement in this GitHub issue. Otherwise, just be sure to add the word “template” to your Pug-related Google searches to avoid the results being full of pooches.

Installing Pug

Before we can get to writing some Pug, we’ll need to install Node, npm (which comes bundled with Node) and the pug-cli package.

There’s a couple options for installing Node/npm. Either head on over to the project’s home page and download the correct binaries for your system, or use a version manager such as nvm. I would recommend using a version manager where possible, as this will allow you to install different Node versions and switch between them at will. It will also negate a bunch of potential permissions errors.

You can check out our tutorial “Installing Multiple Versions of Node.js Using nvm” for a more in-depth guide.

Once Node and npm are installed on your system, you can install the pug-cli package like so:

npm i -g pug-cli

You can check that the install process ran correctly by typing pug --version into a terminal. This will output the version of Pug and the version of the CLI that you have installed.

At the time of writing, this was as follows:

$ pug --version pug version: 2.0.3 pug-cli version: 1.0.0-alpha6 Syntax Highlighting in Your Editor

If your editor doesn’t offer syntax highlighting for Pug, it’d be a good idea to look for an extension to add this functionality.

I’m currently using Sublime Text 3 and, out of the box, this is what a .pug file looks like:

Pug without syntax highlighting

To remedy this, one can install the Sublime Pug package:

Pug with syntax highlighting

Syntax highlighting will make it much easier to work with Pug files, especially those of any length.

Try Pug without Installing

If you’d like to follow along with the simpler examples in this tutorial, you can also run them in various online code playgrounds.

CodePen, for example, has Pug support baked right in. Simply create a new pen, then select Settings > HTML and choose Pug as your preprocessor. This will allow you to enter Pug code into the HTML pane and see the result appear in real time.

As an added bonus, you can click on the down arrow in the HTML pane and select View Compiled HTML to see the markup that Pug has generated.

Pug’s Basic Syntax

Now that we’ve got Pug installed, let’s try it out. Create a new directory named pug-examples and change into it. Then create a further directory called html and a file called index.pug:

mkdir -p pug-examples/html cd pug-examples touch index.pug

Note: the touch command is Linux/macOS specific. Windows users would do echo.> index.pug to achieve the same thing.

The way this is going to work is that we’ll write our Pug code in index.pug and have the pug-cli watch this file for changes. When it detects any, it will take the contents of index.pug and render it as HTML in the html directory.

To kick this off, open a terminal in the pug-examples directory and enter this:

pug -w . -o ./html -P

You should see something like the following:

watching index.pug rendered /home/jim/Desktop/pug-examples/html/index.html

Note: in the above command, the -w option stands for watch, the dot tells Pug to watch everything in the current directory, -o ./html tells Pug to output its HTML in the html directory and the -P option prettifies the output.

Now let’s create the page from the screenshot above (the one complaining about the lack of syntax highlighting). Enter the following into index.pug:

doctype html html(lang='en') head title Hello, World! body h1 Hello, World! div.remark p Pug rocks!

Save pug.index and then inspect the contents of ./html/index.html. You should see the following:

<!DOCTYPE html> <html lang="en"> <head> <title>Hello, World!</title> </head> <body> <h1>Hello, World!</h1> <div class="remark"> <p>Pug rocks!!</p> </div> </body> </html>

Not bad, eh? The Pug CLI has taken our Pug file and rendered it as regular HTML.

This example serves to highlight a couple of important points about Pug. Firstly, it is whitespace sensitive, which means that Pug uses indentation to work out which tags are nested inside each other. For example:

div.remark p Pug rocks!!

The code above produces this:

<div class="remark"> <p>Pug rocks!!</p> </div>

Now take this code:

div.remark p Pug rocks!!

This produces the following:

<div class="remark"></div> <p>Pug rocks!!</p>

It doesn’t really matter what level of indentation you use (you can even use tabs if you have to), but it’s highly recommended that you keep the level of indentation consistent. In this article I’ll be using two spaces.

Secondly, Pug doesn’t have any closing tags. This will obviously save you a fair few keystrokes and affords Pug a clean and easy-to-read syntax.

Now that we’ve got a handle on some basic Pug, let’s quickly go over its syntax. If any of this seems confusing, or you’d like to go more in-depth, be sure to consult the project’s excellent documentation.

The post A Beginner’s Guide to Pug appeared first on SitePoint.

Web Design Agencies: Are You Using These Life-saving Tools & Resources?

May 14, 2019

Description:

This sponsored article was provided by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

Digital design technology is forever changing. Design trends come, and design trends go. Some design tools keep pace with the latest trends, and some don't.

An effective way to keep a competitive edge is to maintain an awareness of the best tools and resources. You need to know where you might be able to use them to your advantage.

There's a problem with that approach. It's that you'll find yourself having to sort among an embarrassment of riches. Not all tools and resources can qualify as being top-of-the-line of course. To find the best of the best can involve quite a bit of searching.

We've pulled together a nice little collection of top site, tools, apps, and resources. All of them are designed to make your work easier, and keep you up with the times. They can help you maintain that competitive edge.

Starting with:

The post Web Design Agencies: Are You Using These Life-saving Tools & Resources? appeared first on SitePoint.

SitePoint Premium New Releases: Clojure, npm, Gulp, Django & More

May 10, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Professional Clojure

Designed for professional devs, this book explains how to parse the difference between functional and object-oriented programming, how to understand Clojure performance and capabilities, how to develop reactive web pages using ClojureScript, and how to adopt an REPL-driven development workflow.

Read Professional Clojure.

A Beginner’s Guide to npm, the Node Package Manager

Learn how to use npm, the command-line tool for interacting with a huge repository of Node.js projects. Discover how to install packages in local and global mode, as well as delete, update and install a certain version of a package. You'll also see how how to manage a project’s dependencies.

Read A Beginner’s Guide to npm, the Node Package Manager.

Django 2 Web Development Cookbook Third Edition

Create fast, robust and secure web apps with the Django Web Framework and Python 3.6. Discover solutions to a variety of web app scenarios. Understand URL routing, models, forms, templates, and RESTful services with Django 2.14. Test, deploy, and scale your web apps efficiently with AWS.

Read Django 2 Web Development Cookbook Third Edition.

An Introduction to Gulp.js

In this guide, we'll introduce Gulp.js. We'll start out by installing Gulp and using it to carry out some basic tasks, such as compressing images, and then move on to using it for more advanced tasks, like populating a database.

Read An Introduction to Gulp.js.

Handbook of Usability Testing

This book digs into how to make products user-friendly, with guidelines on testing, factors that limit usability, choosing and training test moderators, collecting and reviewing data, reporting results and making recommendations, user-centered design principles and practices, and much more.

Read Handbook of Usability Testing.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our 7 day free trial for a spin.

The post SitePoint Premium New Releases: Clojure, npm, Gulp, Django & More appeared first on SitePoint.

Explore GraphQL with Apollo & React: Build a Superhero Database

May 8, 2019

Description:

Curious about all the buzz surrounding GraphQL, but not quite sure why you should be excited? You're in the right place! We'll shed some light on what GraphQL is and give you an opportunity for some hands-on experience.

Let's start by clearing the air and answering the $20,000 question: what is GraphQL? No, it's not an obscure function on your TI-89. It's a query language at heart — or query specification more accurately — that can be used to fetch data from just about any data source.

Better yet, it allows you to fetch the exact data you need — no more, no less — in a single network request. While that may not sound like the sexiest tech to come out of the Facebook factory of innovation, you may just find yourself pleasantly surprised at how useful it can be.

All that's needed is an Apollo server to act as our endpoint and a React app using the Apollo client to leverage any data within. We'll tackle the server first.

Getting Started with Apollo Server

To get our Apollo server started, create a folder called apollo-server in your favorite working directory. Next, enter that directory and run the following npm command — you do have npm and Node installed, right? — to get the Apollo framework in place:

The post Explore GraphQL with Apollo & React: Build a Superhero Database appeared first on SitePoint.

SitePoint Premium New Releases: Git, Cybersecurity, DevOps + More

May 3, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Professional Git

Professional Git

This book gets you into the Git mindset, explaining the basic Git model and overall workflow, the Git versions of common source management concepts and commands, how to track changes, work with branches, and take advantage of Git's full functionality, and how to avoid trip-ups and missteps.

Read Professional Git.

WordPress Plugin Development

WordPress Plugin Development Cookbook

This book presents detailed, step-by-step recipes, explanations and code examples for creating WordPress 4.x plugins. Learn how to extend WordPress, how to use the WordPress plugin API, and how to mold WordPress to your project's needs.

Read WordPress Plugin Development Cookbook.

Cybersecurity Essentials

Cybersecurity Essentials

A comprehensive introduction to cybersecurity concepts and practices, with expert coverage of essential topics required for entry-level cybersecurity certifications. Learn security and surveillance fundamentals, how to secure and protect remote access, how to identify threats and form an effective defense.

Read Cybersecurity Essentials.

Profitable Side Project Handbook

The Profitable Side Project Handbook

Do you dream of being able to earn money while you sleep? Of seeing sales come in while you are out for dinner? Of creating a great product that is sustainable as a real, profitable business? This book will help you to launch your own revenue generating side project.

Read The Profitable Side Project Handbook.

DevOps with Vagrant

Hands-On DevOps with Vagrant

Use Vagrant to easily build complete development environments. Implement DevOps with Vagrant effectively. Integrate Vagrant with different tools such as Puppet, Chef, and Docker. Manage infrastructure with a practical approach.

Read Hands-On DevOps with Vagrant.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. If you're not a member yet, check out our library for $14.99/month.

The post SitePoint Premium New Releases: Git, Cybersecurity, DevOps + More appeared first on SitePoint.

6 Collaborative Coding Tools for Remote Pair Programming

May 2, 2019

Description:

Fifteen years ago, most online collaboration and remote work involved email threads, Skype calls, and endlessly re-zipping projects for sharing after each iteration.

Things have changed a lot — most things for better (Google Docs!) and some things for worse (always-on messaging). Either way, it's fair to say that a lot of the friction has been removed from remote work.

One traditionally high friction area has been cracking real-time code collaboration. But that's been changing in recent years as developers working on the world's top code editors have put forward their solutions.

Whether you work on a distributed team and need collaborative coding tools to serve you every day, or just need something for the occasional problem-solving session with a friend, you'll find something you can use here.

1. Visual Studio Live Share

Visual Studio Live Share

Visual Studio Live Share is Microsoft's own real-time collaborative development solution for Visual Studio and Visual Studio Code.

Live Share allows teams to collaborate on a shared codebase easily — nobody needs to clone a repo, and everyone can use their own development environment. Each person can perform actions like navigating between files, making changes to code, selecting text, and see them reflected for everyone immediately.

Live Share shares everything from files to terminals and audio, offers features for collaborative debugging, and is free. If you're already a VS Code user, this choice is a no-brainer.

While you're at it, check out our VS Code extension recommendations for JavaScript developers.

2. Teletype for Atom

Teletype for Atom

The post 6 Collaborative Coding Tools for Remote Pair Programming appeared first on SitePoint.

Introduction to Nest.js for Angular Developers

May 1, 2019

Description:

In this post, we'll be introducing Nest.js for Angular developers. Nest.js is particularly interesting for them since it was heavily inspired by Angular and built for TypeScript. So what's Nest.js?

Nest.js is an open source MIT-licensed progressive Node framework, written in TypeScript and sharing many concepts with Angular. It's for the server side and can be used to build efficient, reliable and scalable web applications for the enterprise. It's built by Kamil Mysliwiec.

Nest.js combines the best concepts of Object Oriented Programming, Functional Programming and Functional Reactive Programming.

Nest.js has a plethora of features such as:

The post Introduction to Nest.js for Angular Developers appeared first on SitePoint.

Build a Slack App in 10 Minutes with MongoDB Stitch

Apr 30, 2019

Description:

Slack integrations for better collaboration

This article was originally published on MongoDB. Thank you for supporting the partners who make SitePoint possible.

Slack is not only the fastest growing startup in history, but it's also an app by the same name and one of the most popular communication tools in use today. We use it extensively at MongoDB to foster efficient communications between teams and across the company. We're not alone. It seems like every developer I encounter uses it in their company as well.

One interesting thing about Slack (and there are many) is its extensibility. There are several ways you can extend Slack. Building chatbots, applications that interface with the communication service and extending Slack through the introduction of additional commands called "slash commands" that enable Slack users to communicate with external services. In this article, we'll build a simple slash command that enables users to store and retrieve data in and from a MongoDB database. I'm always finding interesting information on the internet that I want to share with my team members so let's build an application we'll call URL Stash that will store interesting URLs for later retrieval via a Slack slash command. Now, follow along in the video below or skip over the video and read on for the details.

https://www.youtube.com/watch?v=FLSvZ2WmYzc

Create a Slack App

Start by logging into your slack team, or you can create a new one for testing. Visit the Slack API Console to create a new Slack App.

The post Build a Slack App in 10 Minutes with MongoDB Stitch appeared first on SitePoint.

An Introduction to Gulp.js

Apr 30, 2019

Description:

Gulp

Developers spend precious little time coding. Even if we ignore irritating meetings, much of the job involves basic tasks which can sap your working day:

generating HTML from templates and content files compressing new and modified images compiling Sass to CSS code removing console and debugger statements from scripts transpiling ES6 to cross-browser–compatible ES5 code code linting and validation concatenating and minifying CSS and JavaScript files deploying files to development, staging and production servers.

Tasks must be repeated every time you make a change. You may start with good intentions, but the most infallible developer will forget to compress an image or two. Over time, pre-production tasks become increasingly arduous and time-consuming; you'll dread the inevitable content and template changes. It's mind-numbing, repetitive work. Wouldn’t it be better to spend your time on more profitable jobs?

If so, you need a task runner or build process.

That Sounds Scarily Complicated!

Creating a build process will take time. It's more complex than performing each task manually, but over the long term, you’ll save hours of effort, reduce human error and save your sanity. Adopt a pragmatic approach:

Automate the most frustrating tasks first. Try not to over-complicate your build process. An hour or two is more than enough for the initial setup. Choose task runner software and stick with it for a while. Don't switch to another option on a whim.

Some of the tools and concepts may be new to you, but take a deep breath and concentrate on one thing at a time.

Task Runners: the Options

Build tools such as GNU Make have been available for decades, but web-specific task runners are a relatively new phenomenon. The first to achieve critical mass was Grunt — a Node.js task runner which used plugins controlled (originally) by a JSON configuration file. Grunt was hugely successful, but there were a number of issues:

Grunt required plugins for basic functionality such as file watching. Grunt plugins often performed multiple tasks, which made customisation more awkward. JSON configuration could become unwieldy for all but the most basic tasks. Tasks could run slowly because Grunt saved files between every processing step.

Many issues were addressed in later editions, but Gulp had already arrived and offered a number of improvements:

Features such as file watching were built in. Gulp plugins were (mostly) designed to do a single job. Gulp used JavaScript configuration code that was less verbose, easier to read, simpler to modify, and provided better flexibility. Gulp was faster because it uses Node.js streams to pass data through a series of piped plugins. Files were only written at the end of the task.

Of course, Gulp itself isn't perfect, and new task runners such as Broccoli.js, Brunch and webpack have also been competing for developer attention. More recently, npm itself has been touted as a simpler option. All have their pros and cons, but Gulp remains the favorite and is currently used by more than 40% of web developers.

Gulp requires Node.js, but while some JavaScript knowledge is beneficial, developers from all web programming faiths will find it useful.

What About Gulp 4?

This tutorial describes how to use Gulp 3 — the most recent release version at the time of writing. Gulp 4 has been in development for some time but remains a beta product. It's possible to use or switch to Gulp 4, but I recommend sticking with version 3 until the final release.

Step 1: Install Node.js

Node.js can be downloaded for Windows, macOS and Linux from nodejs.org/download/. There are various options for installing from binaries, package managers and docker images, and full instructions are available.

Note for Windows users: Node.js and Gulp run on Windows, but some plugins may not install or run if they depend on native Linux binaries such as image compression libraries. One option for Windows 10 users is the new bash command-line, which solves many issues.

Once installed, open a command prompt and enter:

node -v

This reveals the version number. You're about to make heavy use of npm — the Node.js package manager which is used to install modules. Examine its version number:

npm -v

Note for Linux users: Node.js modules can be installed globally so they’re available throughout your system. However, most users will not have permission to write to the global directories unless npm commands are prefixed with sudo. There are a number of options to fix npm permissions and tools such as nvm can help, but I often change the default directory. For example, on Ubuntu/Debian-based platforms:

cd ~ mkdir .node_modules_global npm config set prefix=$HOME/.node_modules_global npm install npm -g

Then add the following line to the end of ~/.bashrc:

export PATH="$HOME/.node_modules_global/bin:$PATH"

Finally, update with this:

source ~/.bashrc Step 2: Install Gulp Globally

Install Gulp command-line interface globally so the gulp command can be run from any project folder:

npm install gulp-cli -g

Verify Gulp has installed with this:

gulp -v Step 3: Configure Your Project

Note for Node.js projects: you can skip this step if you already have a package.json configuration file.

Presume you have a new or pre-existing project in the folder project1. Navigate to this folder and initialize it with npm:

cd project1 npm init

You’ll be asked a series of questions. Enter a value or hit Return to accept defaults. A package.json file will be created on completion which stores your npm configuration settings.

Note for Git users: Node.js installs modules to a node_modules folder. You should add this to your .gitignore file to ensure they’re not committed to your repository. When deploying the project to another PC, you can run npm install to restore them.

For the remainder of this article, we'll presume your project folder contains the following sub-folders:

src folder: preprocessed source files

This contains further sub-folders:

html - HTML source files and templates images — the original uncompressed images js — multiple preprocessed script files scss — multiple preprocessed Sass .scss files

build folder: compiled/processed files

Gulp will create files and create sub-folders as necessary:

html — compiled static HTML files images — compressed images js — a single concatenated and minified JavaScript file css — a single compiled and minified CSS file

Your project will almost certainly be different but this structure is used for the examples below.

Tip: If you're on a Unix-based system and you just want to follow along with the tutorial, you can recreate the folder structure with the following command:

mkdir -p src/{html,images,js,scss} build/{html,images,js,css} Step 4: Install Gulp Locally

You can now install Gulp in your project folder using the command:

npm install gulp --save-dev

This installs Gulp as a development dependency and the "devDependencies" section of package.json is updated accordingly. We’ll presume Gulp and all plugins are development dependencies for the remainder of this tutorial.

Alternative Deployment Options

Development dependencies are not installed when the NODE_ENV environment variable is set to production on your operating system. You would normally do this on your live server with the Mac/Linux command:

export NODE_ENV=production

Or on Windows:

set NODE_ENV=production

This tutorial presumes your assets will be compiled to the build folder and committed to your Git repository or uploaded directly to the server. However, it may be preferable to build assets on the live server if you want to change the way they are created. For example, HTML, CSS and JavaScript files are minified on production but not development environments. In that case, use the --save option for Gulp and all plugins, i.e.

npm install gulp --save

This sets Gulp as an application dependency in the "dependencies" section of package.json. It will be installed when you enter npm install and can be run wherever the project is deployed. You can remove the build folder from your repository since the files can be created on any platform when required.

Step 4: Create a Gulp Configuration File

Create a new gulpfile.js configuration file in the root of your project folder. Add some basic code to get started:

// Gulp.js configuration var // modules gulp = require('gulp'), // development mode? devBuild = (process.env.NODE_ENV !== 'production'), // folders folder = { src: 'src/', build: 'build/' } ;

This references the Gulp module, sets a devBuild variable to true when running in development (or non-production mode) and defines the source and build folder locations.

ES6 note: ES5-compatible JavaScript code is provided in this tutorial. This will work for all versions of Gulp and Node.js with or without the --harmony flag. Most ES6 features are supported in Node 6 and above so feel free to use arrow functions, let, const, etc. if you're using a recent version.

gulpfile.js won't do anything yet because you need to …

Step 5: Create Gulp Tasks

On its own, Gulp does nothing. You must:

install Gulp plugins, and write tasks which utilize those plugins to do something useful.

It's possible to write your own plugins but, since almost 3,000 are available, it's unlikely you'll ever need to. You can search using Gulp's own directory at gulpjs.com/plugins/, on npmjs.com, or search "gulp something" to harness the mighty power of Google.

Gulp provides three primary task methods:

gulp.task — defines a new task with a name, optional array of dependencies and a function. gulp.src — sets the folder where source files are located. gulp.dest — sets the destination folder where build files will be placed.

Any number of plugin calls are set with pipe between the .src and .dest.

The post An Introduction to Gulp.js appeared first on SitePoint.

SitePoint Premium New Releases: Docker, Redux, & Interviews

Apr 26, 2019

Description:

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them.

Learning Docker - Second Edition

Docker lets you create, deploy, and manage scalable app containers across multiple platforms. Learn how to package apps and build, ship, and scale containers. Delve into microservice architecture. Explore real-world examples of securing and managing Docker containers.

Read Learning Docker - Second Edition.

Programming Interviews Exposed

With up-to-date advice on how to succeed in programming job interviews, this book discusses what interviewers need to hear, approaching phone screens with non-technical recruiters, examining common interview problems and tests, demonstrating your skills verbally, in contests, on GitHub, and more.

Read Programming Interviews Exposed.

Learning Redux

With Redux, build consistent web apps that run in different environments (client, server and native), and are easy to test, by centralizing the state of your app. Take your web apps to the next level by combining the power of Redux with other frameworks such as React and Angular.

Read Learning Redux.

And More to Come…

We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. If you're not a member yet, check out our library for $14.99/month.

The post SitePoint Premium New Releases: Docker, Redux, & Interviews appeared first on SitePoint.

How to Build Runnable JavaScript Specifications

Apr 23, 2019

Description:

Programming is not only about giving the computer instructions about how to accomplish a task, it’s also about communicating ideas in a precise way with other people, or even to your future self. Such communication can have multiple goals, maybe to share information or just to allow easier modifications—it’s hard to change something if you don’t understand it or if you don’t remember what you did long time ago. Documentation is key, either as simple comments in your code or as whole documents describing the overall functionality of a program.

A Simple JavaScript Specification File

When we write software we also need to make sure that the code has the intended functionality. While there are formal methods to define semantics, the easiest and quickest (but less rigorous) way is to put that functionality into use and see if it produces the expected results.

Most developers are familiar with these practices: code documentation as comments to make explicit the goal of a block of code, and a series of tests to make sure functions give the desired output.

But usually the documentation and testing is done in different steps, and by unifying these practices, we can offer a better experience for anyone involved in the development of a project. This article explores as simple implementation of a program to run JavaScript specifications that work for both documentation and testing.

We are going to build a command-line interface that finds all the specification files in a directory, extracts all the assertions found inside each specification and evaluates their result, finally showing the results of which assertions failed and which ones passed.

The Specification Format

Each specification file will export a single string from a template literal. The first line can be taken as the title of the specification. The template literal will allow us to embed JS expressions between the string and each expression will represent an assertion. To identify each assertion we can start the line with a distinctive character, in this case, we can use the combination of the bar character (|) and a dash (-), which resembles a turnstile symbol that can sometimes be found as a symbolic representation for logical assertions.

The following is an example with some explanations of its use:

The post How to Build Runnable JavaScript Specifications appeared first on SitePoint.

Optimize the Performance of a Vue App with Async Components

Apr 18, 2019

Description:

Optimize the Performance of a Vue App with Async Components

Single-page applications sometimes cop a little flack for their slow initial load. This is because traditionally, the server will send a large bundle of JavaScript to the client, which must be downloaded and parsed before anything is displayed on the screen. As you can imagine, as your app grows in size, this can become more and more problematic.

Luckily, when building a Vue application using Vue CLI (which uses webpack under the hood), there are a number of measures one can take to counteract this. In this article, I’ll demonstrate how make use of both asynchronous components and webpack’s code-splitting functionality to load in parts of the page after the app’s initial render. This will keep the initial load time to a minimum and give your app a snappier feel.

To follow this tutorial, you need a basic understanding of Vue.js and optionally Node.js.

Async Components

Before we dive into creating asynchronous components, let’s take a look at how we normally load a component. To do so, we’ll use a very simple message component:

<!-- Message.vue --> <template> <h1>New message!</h1> </template>

Now that we’ve created our component, let’s load it into our App.vue file and display it. We can just import the component and add it to the components option so we can use it in our template:

<!-- App.vue --> <template> <div> <message></message> </div> </template> <script> import Message from "./Message"; export default { components: { Message } }; </script>

But what happens now? The Message component will be loaded whenever the application is loaded, so it’s included in the initial load.

This might not sound like a huge problem for a simple app, but consider something more complex like a web store. Imagine that a user adds items to a basket, then wants to check out, so clicks the checkout button which renders a box with all details of the selected items. Using the above method, this checkout box will be included in the initial bundle, although we only need the component when the user clicks the checkout button. It’s even possible that the user navigates through the website without ever clicking the checkout button, meaning that it doesn’t make sense to waste resources on loading this potentially unused component.

To improve the efficiency of the application, we can combine both lazy loading and code splitting techniques.

Lazy loading is all about delaying the initial load of a component. You can see lazy loading in action on sites like medium.com, where the images are loaded in just before they’re required. This is useful, as we don’t have to waste resources loading all the images for a particular post up front, as the reader might skip the article halfway down.

The code splitting feature webpack provides allows you to split your code into various bundles that can then be loaded on demand or in parallel at a later point in time. It can be used to load specific pieces of code only when they’re required or used.

Dynamic Imports

Luckily, Vue caters for this scenario using something called dynamic imports. This feature introduces a new function-like form of import that will return a Promise containing the requested (Vue) component. As the import is a function receiving a string, we can do powerful things like loading modules using expressions. Dynamic imports have been available in Chrome since version 61. More information about them can be found on the Google Developers website.

The code splitting is taken care of by bundlers like webpack, Rollup or Parcel, which understand the dynamic import syntax and create a separate file for each dynamically imported module. We’ll see this later on in our console’s network tab. But first, let’s take a look at the difference between a static and dynamic import:

// static import import Message from "./Message"; // dynamic import import("./Message").then(Message => { // Message module is available here... });

Now, let’s apply this knowledge to our Message component, and we’ll get an App.vue component that looks like this:

<!-- App.vue --> <template> <div> <message></message> </div> </template> <script> import Message from "./Message"; export default { components: { Message: () => import("./Message") } }; </script>

As you can see, the import() function will resolve a Promise that returns the component, meaning that we’ve successfully loaded our component asynchronously. If you take a look in your devtools’ network tab, you’ll notice a file called 0.js that contains your asynchronous component.

Code splitting webpack

Conditionally Loading Async Components

Now that we have a handle on asynchronous components, let’s truly harvest their power by only loading them when they’re really needed. In the previous section of this article, I explained the use case of a checkout box that’s only loaded when the user hits the checkout button. Let’s build that out.

Project Setup

If you don’t have Vue CLI installed, you should grab that now:

npm i -g @vue/cli

Next, use the CLI to create a new project, selecting the default preset when prompted:

vue create my-store

Change into the project directory, then install the ant-design-vue library, which we’ll be using for styling:

cd my-store npm i ant-design-vue

Next, import the Ant Design library in src/main.js:

import 'ant-design-vue/dist/antd.css'

Finally, create two new components in src/comonents, Checkout.vue and Items.vue:

touch src/components/{Checkout.vue,Items.vue}

The post Optimize the Performance of a Vue App with Async Components appeared first on SitePoint.

How to Build a Sales Funnel with Vue.js

Apr 17, 2019

Description:

A sales funnel is an online marketing tool that is built and designed to capture leads from traffic and convert them into customers. They tend to convert 20% to 50% higher than ordinary web pages. A sales funnel typically consists of opt-in pages, order forms, shopping carts, checkout pages and email marketing software. Building such a system is not a walk in the park.

The common way of building a sales funnel today is by purchasing a monthly subscription plan from a sales funnel builder platform. The most popular provider currently charges about $100 to $300. There are other affordable options. However, you may encounter limitations or technical challenges with any provider you work with — some more severe than others.

If you don't want to pay for a subscription plan, then you will have to build one yourself. Historically, coding your own funnel has been more expensive and time-consuming. However, we are living in 2019. The technology used by web developers today has improved immensely in the last 10 years.

It's easier and faster to build and deploy a web application. We have tons of third-party providers that allow integrations to their platforms via remote APIs. This allows us to easily implement heavy-duty features without having to write the code ourselves.

The benefits of owning your own funnel code means your business will be more resilient. You can easily switch servers if something doesn't work out with your provider. You can also easily scale up your online business without meeting major obstacles.

In this tutorial, I'll show you how to code your own simple sales funnel with Vue that will help you promote a product or service that you are selling to consumers. We'll build a simple squeeze page funnel for collecting leads for your email list.

Prerequisites

This article assumes that you have at least a solid grasp in:

Modern JavaScript ES6+ A beginner's knowledge in Vue.js

You'll need to have a modern version of Node.js and the Vue CLI tool installed in your system. At the time of writing this article, Node v10.15.1 was the current LTS. The current Vue CLI version tool is v3.4.1. My personal recommendation is to use nvm to keep your Node.js environment up-to-date. To install the Vue.js CLI tool, execute the command:

npm install @vue/cli

The post How to Build a Sales Funnel with Vue.js appeared first on SitePoint.

How to Build a Stunning Portfolio Website as a Web Developer

Apr 16, 2019

Description:

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

In your role as a professional web developer, you're up for just about any website-building challenge. But, building a creative website portfolio for your own services isn't something you're accustomed to.

As much as you love web development, you've probably never thought of it as being a particularly sexy or creative profession.

The truth is, it's not all that difficult to put an eye-grabbing portfolio together rather easily when you're armed with the right tools, and you have a selection of inspiring and relevant concepts to choose from.

Here are 8 powerful ideas, together with 32 examples, to inspire you and enable you to promote your services on your own stunning portfolio website.

The post How to Build a Stunning Portfolio Website as a Web Developer appeared first on SitePoint.

A Beginner’s Guide to npm — the Node Package Manager

Apr 16, 2019

Description:

Node.js makes it possible to write applications in JavaScript on the server. It's built on the V8 JavaScript runtime and written in C++ — so it's fast. Originally, it was intended as a server environment for applications, but developers started using it to create tools to aid them in local task automation. Since then, a whole new ecosystem of Node-based tools (such as Grunt, Gulp and Webpack) has evolved to transform the face of front-end development.

This popular article was updated on 08.06.2017 to reflect the current state of npm, as well as the changes introduced by the release of version 5.

To make use of these tools (or packages) in Node.js we need to be able to install and manage them in a useful way. This is where npm, the Node package manager, comes in. It installs the packages you want to use and provides a useful interface to work with them.

In this article I'm going to look at the basics of working with npm. I will show you how to install packages in local and global mode, as well as delete, update and install a certain version of a package. I'll also show you how to work with package.json to manage a project's dependencies. If you're more of a video person, why not sign up for SitePoint Premium and watch our free screencast: What is npm and How Can I Use It?.

But before we can start using npm, we first have to install Node.js on our system. Let's do that now...

Installing Node.js

Head to the Node.js download page and grab the version you need. There are Windows and Mac installers available, as well as pre-compiled Linux binaries and source code. For Linux, you can also install Node via the package manager, as outlined here.

For this tutorial we are going to use v6.10.3 Stable. At the time of writing, this is the current Long Term Support (LTS) version of Node.

Tip: You might also consider installing Node using a version manager. This negates the permissions issue raised in the next section.

Let's see where node was installed and check the version.

$ which node /usr/bin/node $ node --version v6.10.3

To verify that your installation was successful let's give Node's REPL a try.

$ node > console.log('Node is running'); Node is running > .help .break Sometimes you get stuck, this gets you out .clear Alias for .break .exit Exit the repl .help Show repl options .load Load JS from a file into the REPL session .save Save all evaluated commands in this REPL session to a file > .exit

The Node.js installation worked, so we can now focus our attention on npm, which was included in the install.

$ which npm /usr/bin/npm $ npm --version 3.10.10 Node Packaged Modules

npm can install packages in local or global mode. In local mode it installs the package in a node_modules folder in your parent working directory. This location is owned by the current user. Global packages are installed in {prefix}/lib/node_modules/ which is owned by root (where {prefix} is usually /usr/ or /usr/local). This means you would have to use sudo to install packages globally, which could cause permission errors when resolving third-party dependencies, as well as being a security concern. Lets change that:

Parcel delivery companyTime to manage those packages Changing the Location of Global Packages

Let's see what output npm config gives us.

$ npm config list ; cli configs user-agent = "npm/3.10.10 node/v6.10.3 linux x64" ; userconfig /home/sitepoint/.npmrc prefix = "/home/sitepoint/.node_modules_global" ; node bin location = /usr/bin/nodejs ; cwd = /home/sitepoint ; HOME = /home/sitepoint ; "npm config ls -l" to show all defaults.

This gives us information about our install. For now it's important to get the current global location.

$ npm config get prefix /usr

This is the prefix we want to change, so as to install global packages in our home directory. To do that create a new directory in your home folder.

$ cd ~ && mkdir .node_modules_global $ npm config set prefix=$HOME/.node_modules_global

With this simple configuration change, we have altered the location to which global Node packages are installed. This also creates a .npmrc file in our home directory.

$ npm config get prefix /home/sitepoint/.node_modules_global $ cat .npmrc prefix=/home/sitepoint/.node_modules_global

We still have npm installed in a location owned by root. But because we changed our global package location we can take advantage of that. We need to install npm again, but this time in the new user-owned location. This will also install the latest version of npm.

$ npm install npm --global └─┬ npm@5.0.2 ├── abbrev@1.1.0 ├── ansi-regex@2.1.1 .... ├── wrappy@1.0.2 └── write-file-atomic@2.1.0

Finally, we need to add .node_modules_global/bin to our $PATH environment variable, so that we can run global packages from the command line. Do this by appending the following line to your .profile, .bash_profileor .bashrc and restarting your terminal.

export PATH="$HOME/.node_modules_global/bin:$PATH"

Now our .node_modules_global/bin will be found first and the correct version of npm will be used.

$ which npm /home/sitepoint/.node_modules_global/bin/npm $ npm --version 5.0.2

The post A Beginner’s Guide to npm — the Node Package Manager appeared first on SitePoint.

9 Helpful Tools for React Development

Apr 15, 2019

Description:

This article was created in partnership with Sencha. Thank you for supporting the partners who make SitePoint possible.

React is a collection of tools and libraries that are independent of each other, which can be daunting for React developers with a job to do. The many tools grants plenty of freedom because you can shop around for the best ones for the job at hand. In React, there are many ways to solve a problem so knowing more than a few tools is a good idea. There are tools that are better at certain problems than others, it all depends on the context. Below is a list of tools I find useful in a good sized React project, some are newer than others and some solve a specific problem when working with React - but all of them I've found helpful.

For each React tool, I’ll provide a short summary with basic information before diving a bit deeper with cool things it can do and my thoughts. Keep in mind all these tools are subject to change.

The post 9 Helpful Tools for React Development appeared first on SitePoint.

Getting up and Running with the Vue.js 2.0 Framework

Apr 15, 2019

Description:

Vue.js logo

This article was updated in November 2018, primarily to bring the tooling section up to date.

As soon as the popular JavaScript framework Vue.js released v2, I was eager to give it a spin and see what it’s like to work with. As someone who’s pretty familiar with Angular and React, I was looking forward to seeing the similarities and differences between them and Vue.

Vue 2 sports excellent performance stats, a relatively small payload (the bundled runtime version of Vue weighs in at 30KB once minified and gzipped), along with updates to companion libraries like vue-router and Vuex, the state management library for Vue. There’s far too much to cover in just one article, but keep an eye out for some later articles where we’ll look more closely at various libraries that couple nicely with the core framework.

Inspiration from Other Libraries

As we go through this tutorial, you’ll see many features that Vue has that are clearly inspired by other frameworks. This is a good thing; it’s great to see new frameworks take some ideas from other libraries and improve on them. In particular, you’ll see Vue’s templating is very close to Angular’s, but its components and component lifecycle methods are closer to React’s (and Angular’s, as well).

One such example of this is that, much like React and nearly every framework in JavaScript land today, Vue uses the idea of a virtual DOM to keep rendering efficient. Vue uses a fork of snabbdom, one of the more popular virtual DOM libraries. The Vue site includes documentation on its Virtual DOM rendering, but as a user all you need to know is that Vue is very good at keeping your rendering fast (in fact, it performs better than React in many cases), meaning you can rest assured you’re building on a solid platform.

Components, Components, Components

Much like other frameworks these days, Vue’s core building block is the component. Your application should be a series of components that build on top of each other to produce the final application. Vue.js goes one step further by suggesting (although not enforcing) that you define your components in a single .vue file, which can then be parsed by build tools (we’ll come onto those shortly). Given that the aim of this article is to fully explore Vue and what it feels like to work with, I’m going to use this convention for my application.

A Vue file looks like so:

<template> <p>This is my HTML for my component</p> </template> <script> export default { // all code for my component goes here } </script> <style scoped> /* CSS here * by including `scoped`, we ensure that all CSS * is scoped to this component! */ </style>

Alternatively, you can give each element a src attribute and point to a separate HTML, JS or CSS file respectively if you don’t like having all parts of the component in one file.

Setting Up a Project

Whilst the excellent Vue CLI exists to make setting up a full project easy, when starting out with a new library I like to do it all from scratch so I get more of an understanding of the tools.

These days, webpack is my preferred build tool of choice, and we can couple that with the vue-loader plugin to support the Vue.js component format that I mentioned previously. We’ll also need Babel and the env preset, so we can write all our code using modern JavaScript syntax, as well as the webpack-dev-server, which will update the browser when it detects a file change.

Let’s initialize a project and install the dependencies:

mkdir vue2-demo-project cd vue2-demo-project npm init -y npm i vue npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev

Then create the initial folders and files:

mkdir src touch webpack.config.js src/index.html src/index.js

The project structure should look like this:

. ├── package.json ├── package-lock.json ├── src │ ├── index.html │ └── index.js └── webpack.config.js

Now let’s set up the webpack configuration. This boils down to the following:

Tell webpack to use the vue-loader for any .vue files Tell webpack to use Babel and the env preset for any .js files Tell webpack to generate an HTML file for the dev-server to serve, using src/index.html as a template: //webpack.config.js const VueLoaderPlugin = require('vue-loader/lib/plugin') const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new VueLoaderPlugin(), new HtmlWebPackPlugin({ template: "./src/index.html" }) ] }

Finally, we’ll add some content to the HTML file and we’re ready to go!

<!-- src/index.html --> <!DOCTYPE html> <html> <head> <title>My Vue App</title> </head> <body> <div id="app"></div> </body> </html>

We create an empty div with the ID of app, as this is the element that we’re going to place our Vue application in. I always prefer to use a div, rather than just the body element, as that lets me have control over the rest of the page.

Writing Our First Vue.js App

We’re going to stay true to every programming tutorial ever and write a Vue application that puts “Hello, World!” onto the screen before we dive into something a bit more complicated.

Each Vue app is created by importing the library and then instantiating a new Vue instance:

import Vue from 'vue' const vm = new Vue({ el: '#app', })

We give Vue an element to render onto the page, and with that, we’ve created a Vue application! We pass a selector for the element that we want Vue to replace with our application. This means when Vue runs it will take the div#app that we created and replace it with our application.

The reason we use the variable name vm is because it stands for “View Model”. Although not strictly associated with the “Model View View-Model” (MVVM) pattern, Vue was inspired in part by it, and the convention of using the variable name vm for Vue applications has stuck. Of course, you can call the variable whatever you’d like!

So far, our application isn’t doing anything, though, so let’s create our first component, App.vue, that will actually render something onto the page.

Vue doesn’t dictate how your application is structured, so this one is up to you. I ended up creating one folder per component, in this case App (I like the capital letter, signifying a component), with three files in it:

index.vue script.js style.css mkdir src/App touch src/App/{index.vue,script.js,style.css}

The file structure should now be:

. ├── package.json ├── package-lock.json ├── src │ ├── App │ │ ├── index.vue │ │ ├── srcipt.js │ │ └── style.css │ ├── index.html │ └── index.js └── webpack.config.js

App/index.vue defines the template, then imports the other files. This is in keeping with the structure recommended in the What About Separation of Concerns? section of Vue’s docs.

<!-- src/App/index.vue --> <template> <p>Hello, World!</p> </template> <script src="./script.js"></script> <style scoped src="./style.css"></style>

I like calling it index.vue, but you might want to call it app.vue too so it’s easier to search for. I prefer importing App/index.vue in my code versus App/app.vue, but again you might disagree, so feel free to pick whatever you and your team like best.

For now, our template is just <p>Hello, World!</p>, and I’ll leave the CSS file blank. The main work goes into script.js, which looks like so:

export default { name: 'App', data() { return {} }, }

Doing this creates a component which we’ll give the name App, primarily for debugging purposes, which I’ll come to later, and then defines the data that this component has and is responsible for. For now, we don’t have any data, so we can just tell Vue that by returning an empty object. Later on, we’ll see an example of a component using data.

Now we can head back into src/index.js and tell the Vue instance to render our App component:

import Vue from 'vue' import AppComponent from './App/index.vue' const vm = new Vue({ el: '#app', components: { app: AppComponent, }, render: h => h('app'), })

Firstly, we import the component, trusting webpack and the vue-loader to take care of parsing it. We then declare the component. This is an important step: by default, Vue components are not globally available. Each component must have a list of all the components they’re going to use, and the tag that it will be mapped to. In this case, because we register our component like so:

components: { app: AppComponent, }

This means that in our templates we’ll be able to use the app element to refer to our component.

Finally, we define the render function. This function is called with a helper — commonly referred to as h — that’s able to create elements. It’s not too dissimilar to the React.createElement function that React uses. In this case, we give it the string 'app', because the component we want to render is registered as having the tag app.

More often than not (and for the rest of this tutorial) we won’t use the render function on other components, because we’ll define HTML templates. But the Vue.js guide to the render function is worth a read if you’d like more information.

Once we’ve done that, the final step is to create an npm script in package.json:

"scripts": { "start": "webpack-dev-server --mode development --open" },

Now, run npm run start. Your default browser should open at http://localhost:8080/ and you should see “Hello, World!” on the screen.

Try editing src/index.vue to change the message to something else. If all has gone correctly, webpack-dev-server should refresh the page to reflect your changes.

Yay! We’re up and running with Vue.js.

The post Getting up and Running with the Vue.js 2.0 Framework appeared first on SitePoint.

Function Composition in JavaScript with Array.prototype.reduceRight

Apr 10, 2019

Description:

Functional programming in JavaScript has rocketed in popularity over the last few years. While a handful of its regularly-promoted tenets, such as immutability, require runtime workarounds, the language's first-class treatment of functions has proven its support of composable code driven by this fundamental primitive. Before covering how one can dynamically compose functions from other functions, let's take a brief step back.

What is a Function?

Effectively, a function is a procedure that allows one to perform a set of imperative steps to either perform side effects or to return a value. For example:

function getFullName(person) { return `${person.firstName} ${person.surname}`; }

When this function is invoked with an object possessing firstName and lastName properties, getFullName will return a string containing the two corresponding values:

const character = { firstName: 'Homer', surname: 'Simpson', }; const fullName = getFullName(character); console.log(fullName); // => 'Homer Simpson'

It's worth noting that, as of ES2015, JavaScript now supports arrow function syntax:

const getFullName = (person) => { return `${person.firstName} ${person.surname}`; };

Given our getFullName function has an arity of one (i.e. a single argument) and a single return statement, we can streamline this expression:

const getFullName = person => `${person.firstName} ${person.surname}`;

These three expressions, despite differing in means, all reach the same end in:

creating a function with a name, accessible via the name property, of getFullName accepting a sole parameter, person returning a computed string of person.firstName and person.lastName, both being separated by a space Combining Functions via Return Values

As well as assigning function return values to declarations (e.g. const person = getPerson();), we can use them to populate the parameters of other functions, or, generally speaking, to provide values wherever JavaScript permits them. Say we have respective functions which perform logging and sessionStorage side effects:

The post Function Composition in JavaScript with Array.prototype.reduceRight appeared first on SitePoint.

4 Ways to Grow Your Online Brand by Combining Content & Commerce

Apr 10, 2019

Description:

For years, one of the most significant challenges to scaling a WordPress site was due to the clunky ecommerce options.

Sure, you could use platforms like Shopify, but those take your customers offsite and don't scale well or integrate easily with WordPress. In addition, traditional ecommerce solutions focus on selling, not content.

With 30% of all businesses using WordPress (making it the most widely used content management system on the planet), that left a huge hole in the ecommerce market. Until now.

With the latest addition of BigCommerce for WordPress, growing an online brand using headless commerce solutions is easier than ever.

You no longer have to choose between selling products or focusing on content marketing. Now, you can match different ecommerce sites and platforms with content-driven strategies to create a blog that gets traffic--and makes sales.

So, how do you do it? Here are four strategies for building an online brand by combining the power of content marketing with advanced ecommerce tools.

Develop Your Blog with Niche Content to Attract Leads

Too many people think content market is squishy; they think it is untrackable, unscalable, and incapable of driving sales.

Those people are wrong.

Here's why.

Customers enjoy reading relevant content. It makes them feel closer and more positive about a brand. Consider these stats from Demand Metric:

Image source

Need more proof? How about the fact that 60% of people are inspired to seek out a product after reading content about it? With over 4 million blog posts published daily, it’s a sign that content marketing is here to stay.

Content sells, plain and simple.

How Niche Content Can Help You Drive Leads &Amp; Sell

Instead of creating widely popular content, which is likely to get lost in the ever-growing expanse of the internet, develop and market to a small, niche audience.

Here is how niche marketing helps you sell:

Niche marketing is about understanding who your audience is and taking the time to build a strong, trusting relationship. For instance, take this free piece of content that Freshdesk gives their readers, a customer service resume template:

Image source

This provides instant value for people in the field of customer service, perfectly relating to the products they sell.

Better content like this customer service resume value-add means your competition is less likely to be able to draw your customers away with, for example, slightly lower prices.

Long term, you become a trusted expert; a big fish in a small pond.

And your customers become brand loyal and enter your sales funnel. Let’s look deeper into niche ecommerce content.

What Niche Ecommerce Content Looks Like

So, what does good niche content look like in the commerce field? Are we talking detailed products descriptions, quirky headlines, flawless grammar?

Nope, there is more to it than that.

Good content should always be focused on what is useful to your audience. You can use social media analytics tools to track engagement and tailor your site messaging to match. In the ecommerce field this might mean:

Educating your audience by describing a little-known or little-understood feature. Showing them how to complete a challenging task. Giving a list of resources in your industry. Gift guides for hard to the hard to shop for.

The right type of niche SEO content will depend upon your industry, of course. So, let's look at a few examples of niche content marketing done right.

Mighty Nest

Mighty Nest is a socially conscious ecommerce store dedicated to helping people find eco-friendly, green, and minimal waste products.

Their content addresses the questions and problems many people have when looking for safer alternatives.

Take a look at this post, titled "The Essential Guide to GOOD Skincare Ingredients." This piece blends education — "Here's why these chemicals are bad for your skin." — with product recommendations aimed at a niche audience: people who are looking for healthy skin care alternatives.

Image source

It won't reach the masses, but instead focuses on those who care about natural skin care products.

Grovemade

Here is another example, from company Grovemade. They design, manufacture, and sell beautifully simple items made from natural materials including electronic charging pads, speakers, pen holders, and watches.

The post 4 Ways to Grow Your Online Brand by Combining Content & Commerce appeared first on SitePoint.

The Top 12 Multipurpose WordPress Themes to Choose in 2019

Apr 9, 2019

Description:

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

Some WordPress users tend to avoid using multipurpose themes. They do so for reasons that would seem to make common sense. They subscribe to a popular saying – "jack of all trades, master of none." Here, anything designed to do everything won't do some, if any, of them particularly well.

There are, of course, some multipurpose or all-in-one design tools that simply can't get the job done. Some may be poorly coded or have other faults. But there are plenty that make excellent choices for building almost any type of website.

If there's a problem, it's that there are too many good ones. Finding a responsive theme that fits your needs can be a challenge.

Searching for an alternative to plowing through a whole host of multipurpose themes? Consider checking out this list of our 12 favorite multipurpose themes for 2019.

Starting with the popular…

The post The Top 12 Multipurpose WordPress Themes to Choose in 2019 appeared first on SitePoint.

Fetching Data from a Third-party API with Vue.js and Axios

Apr 9, 2019

Description:

A woman collecting data from library shelves

More often than not, when building your JavaScript application, you’ll want to fetch data from a remote source or consume an API. I recently looked into some publicly available APIs and found that there’s lots of cool stuff that can be done with data from these sources.

A woman collecting data from library shelves

With Vue.js, you can literally build an app around one of these services and start serving content to users in minutes.

I’ll demonstrate how to build a simple news app that will show the top news articles of the day allow users to filter by their category of interest, fetching data from the New York Times API. You can find the complete code for this tutorial here.

Here’s what the final app will look like:

Vue.js news web app

To follow along with this tutorial, you’ll need a very basic knowledge of Vue.js. You can find a great “getting started” guide for that here. I’ll also be using ES6 Syntax, and you can get a refresher on that here.

Project Structure

We’ll keep things very simple by limiting ourselves to just 2 files:

./app.js ./index.html

app.js will contain all the logic for our app, and the index.html file will contain our app’s main view.

We’ll start off with some basic markup in index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>The greatest news app ever</title> </head> <body> <div class="container" id="app"> <h3 class="text-center">VueNews</h3> </div> </body> </html>

Next, include Vue.js and app.js at the bottom of index.html, just before the closing </body> tag:

<script src="https://unpkg.com/vue"></script> <script src="app.js"></script>

Optionally, Foundation can be included, to take advantage of some pre-made styles and make our view look a bit nicer. Include this within the <head> tag:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css"> Creating a Simple Vue App

First, we’ll create a new Vue instance on the element div#app, and mock the response from the news API using some test data:

// ./app.js const vm = new Vue({ el: '#app', data: { results: [ {title: "the very first post", abstract: "lorem ipsum some test dimpsum"}, {title: "and then there was the second", abstract: "lorem ipsum some test dimsum"}, {title: "third time's a charm", abstract: "lorem ipsum some test dimsum"}, {title: "four the last time", abstract: "lorem ipsum some test dimsum"} ] } });

We tell Vue what element to mount on, via the el option, and specify what data our app would be using via the data option.

To display this mock data in our app view, we can write this markup inside the #app element:

<!-- ./index.html --> <div class="columns medium-3" v-for="result in results"> <div class="card"> <div class="card-divider"> {{ result.title }} </div> <div class="card-section"> <p>{{ result.abstract }}.</p> </div> </div> </div>

The v-for directive is used for rendering our list of results. We also use double curly braces to show the contents of each of them.

Note: you can read more on the Vue Template Syntax here.

We now have the basic layout working:

Simple news app with mock data

Fetching Data from the API

To make use of the NYTimes API, you’ll need to get an API key. So if you don’t already have one, head over to their signup page and register to get an API key for the Top Stories API.

Making Ajax Requests and Handling Responses

Axios is a promise-based HTTP client for making Ajax requests, and will work great for our purposes. It provides a simple and rich API. It’s quite similar to the fetch API, but without the need to add a polyfill for older browsers, and some other subtleties.

Note: previously, vue-resource was commonly used with Vue projects, but it has been retired now.

Including axios:

<!-- ./index.html --> <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Now we can make a request to get a list of top stories from the home section, once our Vue app is mounted:

// ./app.js const vm = new Vue({ el: '#app', data: { results: [] }, mounted() { axios.get("https://api.nytimes.com/svc/topstories/v2/home.json?api-key=your_api_key") .then(response => {this.results = response.data.results}) } });

Remember: replace your_api_key with your actual API key obtained from the NYT Dev Network area.

Now we can see the news feed on our app homepage. Don’t worry about the distorted view; we’ll get to that in a bit:

News Feed

The response from the NYT API looks like this, via Vue devtools:

Response from NYT API - Vue.js news app

The post Fetching Data from a Third-party API with Vue.js and Axios appeared first on SitePoint.

7 Cross-Browser Testing Tools You Need in 2019

Apr 8, 2019

Description:

First off, what is cross-browser testing?

Cross-browser testing is the formality of testing web applications and websites in all of the common web browsers that users use today — this ensures that we deliver a consistent user experience everywhere, and not just the web browser that takes our fancy. Here are some of the things to look out for:

Code validation: do some browsers report code errors? Performance: is the website slow, or even causing crashes? Responsive design: is the design consistently responsive? UI inconsistencies: are there any other design flaws? Other strange behaviours: anything else simply not working? What happens if I don’t test?

Inconsistencies are actually very normal. Fact is, all web browsers behave and render websites a little differently, and some browsers might not even support the features we originally aimed to utilize; and when these inconsistencies appear, it can have a direct impact on our revenue (among other things).

Let’s take eCommerce for example. 69.89% of checkouts are abandoned, and 17% of those are attributed to website errors and crashes. Assuming that a business would accrue half a million sales annually, that’s 59,407 sales lost due to errors and crashes that could have been thwarted by cross-browser testing.

Which browsers should I test on?

Since Microsoft announced they’d be ditching their own EdgeHTML and Chakra engines in favor of the widely-adopted Blink and V8 engines, this means many of the major browsers today offer similar levels of code compatibility. While this is a step back in terms of healthy competition, it does mean that if a website works in Google Chrome, it’ll most likely work in Brave, Opera, and soon-to-be Microsoft Edge. That combined with the fact that even Microsoft has instructed us to stop using Internet Explorer, cross-browser testing is easier than it’s ever been before, with only Safari and Firefox using their own engines.

Technically, the web browsers we should be supporting today are the ones that our users and customers are using, information that’s easy enough to find using Google Analytics