You are on page 1of 45

Visual Studio Code: A Power User's Guide

By Michael Wanyoike

Web

April 15, 2020

Share:

In this guide, you’ll learn how to take advantage of Visual Studio Code to
supercharge your development work ow.

This article is written for Visual Studio Code beginners, and users looking to get
more out of the app. VS Code, as it’s commonly known, is considered a
“lightweight” code editor. In comparison with full integrated development
environment (IDE) editors which occupy gigabytes of disk space, VS Code uses
less than 200MB when installed.

Despite the “lightweight” term, Visual Studio Code offers a massive number of
features which keep increasing and improving with every new update. For this
guide, we’ll cover the most popularly used features. Every programmer has their
own toolset that they update whenever they discover new work ows. If you want
to learn every tool and feature VS Code has to offer, check out their o cial
documentation. In addition, you may want to keep track of updates for new and
improved features.

Prerequisites

In order to follow this guide, you need to be pro cient in at least one programming
language and framework. You also need to be conversant with versioning your
project code with git. You’ll also need to have an account with a remote repository
platform such as GitHub. I recommend you setup SSH Keys to connect with your
remote repo.

We’ll use a minimal Next.js project to demonstrate VS Code features. If you’re


new to this, don’t worry — the focus of the guide isn’t the framework or language
used. You can transfer the skills we’ll teach to any language and framework you
work with in Visual Studio Code.

A Bit of History

Not so long ago, these were the fully integrated development environments on
offer:

Visual Studio IDE


NetBeans
Eclipse
IntelliJ IDEA

These platforms provide the complete development work ow, from coding to
testing and deployment. They analyze code, highlight errors, and have all sorts of
other features that provide assistance. They also contain plenty of features that
most developers don’t use, though they are essential for some teams. As a result,
these platforms took a lot of disk space and were slow to start up. Many
developers preferred using advanced text editors such as emacs and vim to write
their code in.

Soon, a new crop of platform independent code editors arrived. These lightweight
editors provided many features that were previously exclusive to IDEs. I’ve listed
them below in the order they were released:

Sublime Text: July 2013


Atom.io: June 2015
Visual Studio Code: April 2016

Mac developers had access to TextMate, which was released in October 2004.
The snippets system used by all of these editors originated from TextMate.
According to a developer survey done by Stack OverFlow in 2019, Visual Studio
Code is the most popular code development environment with 50.7% usage.
Visual Studio IDE comes second, and NotePad++ comes third.

That’s enough history and stats. Let’s show you how to use Visual Studio Code’s
features.

Setup and Updates

Visual Studio Code’s package installer is less than 100MB and consumes less
than 200MB when fully installed. When you visit the download page, it will detect
your operating system and offer you the correct download link.

Updating VS Code is easy. When an update is available, it displays a noti cation


prompt. For Windows users, you’ll have to click on the noti cation to download
and install the latest version. The download process occurs in the background
while you’re working. When it’s ready to install, a restart prompt will appear.
Clicking this will install the update for you and restart VS Code.

For Ubuntu-based distributions, clicking on the update noti cation will simply
open the website for you to download the latest installer. A much easier way is
simply running sudo apt update && sudo apt upgrade -y . This will
update all installed Linux packages including Visual Studio Code. The reason this
works is because VS Code added its repo to your package repo registry during the
initial installation. You can nd the repo information on this path:
/etc/apt/sources.list.d/vscode.list .
User Interface

Let’s rst get acquainted with the user interface:

Image source

Visual Studio Code’s user interface is divided into ve main areas which you can
easily adjust.

Activity Bar: allows you to switch between views: explorer, search, version
control, debug and extensions.
Side Bar: contains the active view.
Editor: this is where you edit les and preview markdown les. You can
arrange multiple open les side-by-side.
Panel: displays different panels: integrated terminal, output panels for debug
information, errors and warnings.
Status: displays information about the currently opened project and le. Also
contains buttons for executing version control actions, and
enabling/disabling extension features.

There’s also the top Menu Bar where you can access the editor’s menu system.
For Linux users, the default integrated terminal will probably be the Bash shell. For
Windows users, it’s PowerShell. Fortunately, there’s a shell selector located inside
the terminal dropdown that will allow you to choose a different shell. If installed,
you can choose any of the following:

Command Prompt
PowerShell
PowerShell Core
Git Bash
WSL Bash

Working with Projects

Unlike full IDEs, Visual Studio Code doesn’t provide project creation or offer
project templates in the traditional way. It simply works with folders. On my Linux
development machine, I’m using the following folder pattern to store and manage
my projects:

/home/{username}/Projects/{company-name}/{repo-provider}/{project-n

The Projects folder is what I refer to as to the workspace. As a freelance


writer and developer, I separate projects based on which company I’m working for,
and which repo I’m using. For personal projects, I store them under my own
ctitious “company name”. For projects that I experiment with for learning
purposes, and which I don’t intend to keep for long, I’ll just use a name such as
play or tuts as a substitute for {repo-provider} .
Learn PHP for free!
Make the leap into server-side programming with a comprehensive cover
of PHP & MySQL.

Normally RRP $39.99 Yours absolutely free

Name

Email

Get the book free

If you’d like to create a new project and open it in VS Code, you can use the
following steps. Open a terminal and execute the following commands:

$ mkdir vscode-demo
$ cd vscode-demo
# Launch Visual Studio Code
$ code .

You can also do this in File Explorer. When you access the mouse context menu,
you should be able to open any folder in VS Code.

If you want to create a new project linked to a remote repo, it’s easier creating one
on the repo site — for example, GitHub or BitBucket.
Take note of all the elds that have been lled in and selected. Next, go to the
terminal and execute the following:

# Navigate to workspace/company/repo folder


$ cd Projects/sitepoint/github/

# Clone the project to your machine


$ git clone git@github.com:{insert-username-here}/vscode-nextjs-dem

# Open project in VS Code


$ cd vscode-nextjs-demo
$ code .
Once the editor is up and running, you can launch the integrated terminal using
the keyboard shortcut Ctrl+~ (tilde key). Use the following commands to
generate package.json and install packages:

# Generate `package.json` file with default settings


$ npm init -y

# Install package dependencies


$ npm install next react react-dom

Next, open package.json and replace the scripts section with this:

"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}

The entire Visual Studio Code window should look like this:
Before we look at the next section, I’d like to mention that VS Code also supports
the concept of multi-root workspaces. If you’re working with related projects —
front-end, back-end, docs etc. — you can manage them all in a single workspace
inside one editor. This will make it easier to keep your source code and
documentation in sync.

Version Control with Git

Visual Studio Code comes built-in with Git source control manager. It provides a
UI interface where you can stage, commit, create new branches and switch to
existing ones. Let’s commit the changes we just did in our project. On the Activity
bar, open the Source Control Panel and locate the Stage All Changes plus button
as shown below.
Click on it. Next, enter the commit message “Installed next.js dependencies”, then
click the Commit button at the top. It has the checkmark icon. This will commit
the new changes. If you look at the status located at the bottom, you’ll see various
status icons at the left-hand corner. The 0 ↓ means there’s nothing to pull from
the remote repo. The 1 ↑ means you’ve got one commit you need to push to
your remote repo. Clicking on it will display a prompt on the action that will take
place. Click OK to pull and push your code. This should sync up your local
repo with the remote repo.

To create a new branch or switch to an existing branch, just click the branch
name master on the status bar, left bottom corner. This will pop up a branch
panel for you to take an action.
Do check out the following extensions for an even better experience with Git:

Git Lens
Git History

Support for a different type of SCM, such as SVN, can be added via installing the
relevant SCM extension from the marketplace.

Creating and Running Code

On the Activity Bar, head back to the Explorer Panel and use the New Folder
button to create the folder pages at the root of the project. Select this folder
and use the New File button to create the le pages/index.js. Copy the following
code:

function HomePage() {
return <div>Welcome to Next.js!</div>;
}

export default HomePage;

With the Explorer Panel, you should see a section called NPM Scripts. Expand on
this and hover over dev . A run button (play icon) will appear next to it. Click on
it and this will launch a Next.js dev server inside the Integrated Terminal.

It should take a few seconds to spin up. Use Ctrl + Click on the URL
http://localhost:3000 to open it in your browser. The page should open
successfully displaying the “Welcome” message. In the next section, we’ll look at
how we can change Visual Studio Code preferences.

User and Workspace Settings

To access VS Code preference settings, use the shortcut key Ctrl + , . You can
also access it via the menu command like this:

On Windows/Linux – File > Preferences > Settings


On macOS – Code > Preferences > Settings
By default, a Settings editor graphical interface should appear. It helps users
make changes to preferences easily, as there are thousands of editable settings
that are available. The Settings editor provides user friendly names and
description for what each setting does. In addition, related settings have been
grouped together and there’s a search bar for locating a speci c setting.

When changing settings using the editor, pay attention to the active scope at the
top. Take note that not all settings can be con gured via the graphical interface.
For that, you have to edit the le settings.json directly. As you scroll down
the Settings editor, you’ll come across a shortcut that will take you to this le.

There are two different scopes that Visual Studio Code settings are classi ed
under:
User Settings: Settings are stored under user account. They will take effect
on all projects your work on.
Workspace: Settings are stored within project or workspace folder. They will
apply only in that speci c project.

Depending on your platform, you can locate VS Code’s user setting in the
following locations:

Windows: %APPDATA%\Code\User\settings.json
macOS: $HOME/Library/Application
Support/Code/User/settings.json
Linux: $HOME/.config/Code/User/settings.json

For Workspace, simply create a folder .vscode at the root of your project. Then
create the le settings.json inside this folder. If working with the Settings
editor panel, it will do this for you automatically when you change settings under
the Workspace scope. Here’s a subset of the global settings I prefer to work with:

{
"editor.minimap.enabled": false,
"window.openFoldersInNewWindow": "on",
"diffEditor.ignoreTrimWhitespace": false,
"files.trimTrailingWhitespace": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"workbench.editor.enablePreview": false,
"workbench.list.openMode": "doubleClick",
"window.openFilesInNewWindow": "default",
"editor.formatOnPaste": true,
"editor.defaultFormatter": "esbenp.prettierVS Code",
"editor.formatOnSave": true,
"editor.tabSize": 2,
"explorer.confirmDelete": false
}
I tend to work with multiple projects simultaneously, hence the setting
window.openFoldersInNewWindow allows me to open new project folders
without closing (replacing) the active one. For editor.defaultFormatter ,
I’ve set it to Prettier, which is an extension I have installed. We’ll discuss this in a
later section shortly. Next, let’s look at language associations.

Language Association

I do a lot of projects using React. Lately, most React frameworks generate


components use the .js extension instead of .jsx . As a result, formatting
and syntax colorization becomes a problem when you start writing JSX code. To
x this, you need to associate .js les with JavaScriptReact . You can
easily do this by changing Language Mode via the Ctrl + Shift + P
command panel. You can also update settings.json by adding this
con guration:

{
"files.associations": {
"*.js": "javascriptreact"
}
}

Next time you open a JS le, it will be treated as a React JSX le. I’ve speci ed
this in my global settings since I often work with React projects. Unfortunately,
doing this breaks a built-in feature called Emmet. It’s a popular plugin that helps
developers autocomplete HTML and CSS code in a very intuitive way. You can x
this issue by adding the following con guration in settings.json :

{
"emmet.includeLanguages": {
"javascript": "javascriptreact"
}
}
Next time you have trouble activating Emmet for a particular le extension or
language, check to see if it can be resolved by adding the language association in
emmet.includeLanguages . For more information, check out the o cial
documentation for VS Code Emmet.

Keyboard Shortcuts

So far, we’ve covered two keyboard shortcuts:

Ctrl + , : Open settings

Ctrl + Shift + P : Open command palette

The Command Palette provides access to Visual Studio Code’s entire


functionality including keyboard shortcuts for common operations. If you install
an extension, any manually triggered actions will be listed here. However, for
extensions such as Prettier and Beautify, they’ll use the same Format command.
Visual Studio Code also has its own built-in formatter plugin. To specify which
plugin should execute the action, you need to go to the Settings editor and
change the Default Formatter con guration. Here’s an example of how I’ve set it
in mine:

{
"editor.defaultFormatter": "esbenp.prettierVS Code"
}

You can also specify a different formatter for a speci c language mode. Here are
several more keyboard shortcuts you need to memorize:

Ctrl + P will let you navigate to any le or symbol by typing its name

Ctrl + Tab will cycle you through the last set of les opened

Ctrl + Shift + O will let you navigate to a speci c symbol in a le

Ctrl + G will let you navigate to a speci c line in a le


Here are my favorite commands I use often while writing code:

Ctrl + D : press multiple times to select identical keywords. When you

start typing, it renames all the selected keywords


Ctrl + Shift + Up/Down : Add Cursor above or below in order to edit

multiple lines at once


Alt + Shift + Click : Add Cursor at multiple locations in order to edit in

different sections of code simultaneously


Ctrl + J : Add 2 or more lines into one. Works perfectly if you’ve a

formatter active as you edit code


Ctrl + F : Search for a keyword in current le

Ctrl + H : Search and replace in current le

Ctrl + Shift + F : Search in all les

If you visit the Menu options, you’ll nd shortcut keys for most commands.
Personally, I’ve never gotten used to some of the default shortcut keys that come
with Visual Studio Code due to using editors such as Atom for a long time. The
solution I found was simply to install the Atom Keymap. This allows me to use the
shortcut key Ctrl + \ to toggle the Side Bar. If you’d like to edit the keyboard
bindings yourself, simply go to the menu under File > Preferences > Keyboard
Shortcuts. (Code > Preferences > Keyboard Shortcuts on macOS).
8.7K views

Code Editor Features

In this section, we’ll quickly look into the various developer-friendly features Visual
Studio Code provides to help you write faster, cleaner and more maintainable
code.

Intellisense
This is a popular feature also known as “code completion” or autocomplete. Out
of the box, VS Code provides Intellisense for:

JavaScript, TypeScript
HTML
CSS, SCSS and Less

As you type your code, a pop with a list of possible options will appear. The more
you type, the shorter the list gets. You can press Enter or Tab once your
intended keyword is highlighted to autocomplete your code. Pressing Esc will
remove the popup. Inserting a . at the end of a keyword or pressing Ctrl +
space bar will trigger the IntelliSense popup to appear.
7.9K views

If you’re working with a language that is not supported out of the box, you can
install a language extension from the marketplace to activate IntelliSense for your
desired programming language. Check out the o cial docs to learn more on how
you can customize IntelliSense.

Snippets
Typing repetitive code such as if statements, for loops and component
declaration can be a bit tiring. You might nd yourself copying and pasting code
to work faster. Fortunately, Visual Studio Code offers a feature called
Snippets , which are simply templates of code. For example, instead of typing
console.log , just type log and IntelliSense will prompt to insert the snippet
for you.

There are many snippets you can access as long as you’ve memorized the
shorthand or keyword that triggers snippet insertion. Since you’re new to this, you
can access a list of all snippets available via Command Palette > Insert Snippets:
Scroll up and down to view the entire list. Take note that most snippets have
tabstops that allow you to replace the relevant sections of code when you insert
them. You can nd more snippet extensions in the marketplace. You can also
create your own. This article shows you how to do both. You can check out the
o cial docs for more information on how to de ne your own snippets.

Formatting
Often when typing or pasting code from different sources, we tend to mix coding
styles. For example:

indenting with space vs tabs


ending with semicolon
double quotes or single quotes
Formatting is important, as it makes the code readable. However, it can be time
consuming when you come across large sections of unformatted code. Luckily,
Visual Studio Code can perform formatting for you with a single command. You
can execute the formatting command via the Command Palette. Visual Studio
Code supports formatting for the following languages out of the box:

JavaScript
TypeScript
JSON
HTML

You can customize Visual Studio Code’s formatting behavior by changing the
following settings to true or false :

editor.formatOnType : format the line after typing


editor.formatOnSave : format a le on save
editor.formatOnPaste : format the pasted content

However, the built-in formatters may not conform to your style of coding. If you’re
working with frameworks such as React, Vue or Angular, you’ll nd that the built-in
formatters tend to mess up your code. You can x this by disabling formatting for
a speci c language:

"html.format.enable": false

However, the best solution is to install a formatter extension from the


marketplace. My favorite is [Prettier](https://marketplace.visualstudio.com/items?
itemName=esbenp.prettierVS Code), as it supports a huge number of languages
including:

Flow · JSX · JSON


CSS · SCSS · Less
Vue · Angular
GraphQL · Markdown · YAML

After installing it, you’ll need to set it as the default formatter:

{
"editor.defaultFormatter": "esbenp.prettierVS Code",
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettierVS Code"
}
}

It’s also recommended you install prettier package locally as a dev


dependency:

npm install prettier -D --save-exact

The default formatting options Prettier enforces may work out for you. If not, you
can customize by creating a .prettierrc con guration le either at the root
of your project or in your home directory. You can place your custom formatting
rules here. Here’s an example:

{
"trailingComma": "all",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}

Feel free to check out other formatting extensions. However, you’ll nd Prettier to
be the most popular.

Linting
A Lint, or Linter is a tool that analyzes your code and checks for syntax errors,
styling issues, calls to undeclared variables, usage of deprecated functions,
misuse of scope and many other issues. Visual Studio Code doesn’t come
shipped in with any Linter. However, it does make it easy setting up one for the
programming language you’re using. For example, if you’re working on new
Python project, you’ll get a prompt to install one for you. You can also open the
Command Palette ( Ctrl + Shift + P ) and select the Python: Select Linter
command.

For JavaScript, you’ll need to install an extension such as ESLint which is the
most popular. This extension requires you to install ESLint as a dev dependency.
You may also need one or more ESLint plugins that will help you lint the coding
style and framework you’re using. You can check out our guide on how to
con gure ESLint. There are also other linter tools you can check out. My
recommendation is to go with ESLint as it’s easier to con gure and supports
more JavaScript styles and frameworks.

Once you’ve set up the linting tool, VS Code will automatically lint your code every
time you save the le. You should also update your package.json scripts to
include a command for running the lint tool.

Debugging
If you use print statements to debug, you should cease and desist as there’s a
better way to debug your code. With VS Code, you can set breakpoints and
inspect variables while your code is running.
Image source

Check out our guide on debugging JavaScript projects with VS Code and
Chrome Debugger for step-by-step instructions on how to debug your code.

Summary

We’ve now come to the end of the guide. As noted earlier, the information here will
help you jump start your way into improving your coding work ow with Visual
Studio Code. I recommend you check out our top 10 must-have extensions for VS
Code. While most VS Code tools are easy to learn and integrate into your
work ow, others need some time to gure out and get used to. Nevertheless,
mastering VS Code features will make you an e cient and better software
developer.

If you want to reach the absolute peak of productive performance with Visual
Studio Code, check out Visual Studio Code: End-to-End Editing and Debugging
Tools for Web Developers. It’s a fantastic book from Wiley that you can read
online (or off!) in our Premium library.
Michael Wanyoike

I write clean, readable and modular code. I love learning new technologies that bring e ciencies and
increased productivity to my work ow.

Latest Remote Jobs

Senior Frontend Engineer


SitePoint
react javascript

.Net Developer
Global Technology
.net sql

Senior Engineer - Data Team


IPinfo
bigquery python

Full Stack Developer


Bottomless

Dev Tools & OSS Architect


Bit
javascript

More Remote Jobs

7 Reasons NOT to Use a Static Site


Generator
By Craig Buckler

Web

May 6, 2021

Share:
Static site generators (SSGs) are popular and offer many bene ts, but this
article discusses reasons why they may not be a suitable replacement for your
content management system (CMS).

In my previous article, we discussed how your site could bene t from using a
static site generator:

A static site is a collection of pages contained in basic HTML les. You


could hand-write these in a text editor, but managing assets and repeated
elements such as navigation can become problematic.
A content management system stores page content in a database and
provides facilities to edit and apply themes. Management becomes easier at
the expense of exibility, performance, server requirements, security, and
backups.
A static site generator is a compromise between using a hand-coded static
site and a full CMS. You generate the full site once using raw data (such as
Markdown les) and templates. The resulting set of les is transferred to
your live server.
The term “Jamstack” (JavaScript, APIs, and Markup) is used in relation to
static sites. It refers to the rise in frameworks, serverless functions, and
associated tools which generate static les but allow complex interactivity to
be added.

Popular static site generators include Jekyll, Eleventy, Gatsby, Hugo, and
Metalsmith. SSGs are available for most languages; see StaticGen for many
more.

SSGs appear to offer the bene ts of both CMS and static worlds, but they may not
be suitable for every project …

1. You’re On Your Own


You won’t get far using a static site generator without some development
expertise. The process is more di cult than using a CMS, there are fewer
resources, and you could struggle to nd pre-built plugins and templates.

Contrast that with WordPress. A non-technical user may require installation


assistance but, once that’s complete, they can edit a site and install one of the
many thousands of themes and plugins available. They may not have the best
bespoke website, but they’re running with minimal intervention.

2. Choice Paralysis

There are many static site generators, but even the most popular tools are used
by a tiny proportion of the web community. You’ll need time to research,
investigate, and evaluate the options. One of the rst SSGs was the Ruby-based
Jekyll but, while you don’t necessarily require Ruby expertise, it will help if you’ve
used the language before.

There are many CMSs, but there’s one obvious choice: WordPress. It powers more
than 40% of the Web, so help is abundant. Again, it will help if you have some PHP
experience, but even a non-developer can create a reasonable website using off-
the-shelf themes and plugins.

3. The Initial Setup Time

Creating your rst static site will take time. You’ll need to learn the build process,
and much of the template code will need to be developed. Deployment scripts
may also be necessary.

Developing a custom CMS theme can also be complicated, but pre-built


templates are available and assistance is easier to nd. Further development may
not be required following the initial installation.
4. No Administration Interface

Clients may be cautious when faced with a complex CMS interface. Asking them
to create and edit a set of Markdown les may terrify many. You can make the
process easier by perhaps:

using their existing CMS as an SSG data source, or


providing simpler work ows, such as editing Git-based les in StackEdit or
Hackmd.io.

But this will further impact your initial development time.

5. Website Consistency

Static sites are exible: anything contained within source content can be rendered
on a web page. Users may be able to include scripts, widgets, or numerous
undesired items.

A CMS can be con gured to constrain the user. Content is normally bound to a
database with speci c elds, so administration panels prompt the user to enter a
title, body content, excerpts, featured images, and so on. Even if the user enters
something in an unexpected eld, it won’t appear on the website unless it’s
implemented within the theme template.

6. Managing Large Sites

Consider a website with thousands of pages, daily content publications, real-time


breaking news, and dozens of authors in multiple locations. It’s possible to
manage content using a static site generator, but:
Content editing and publishing can be more awkward. Editors may require
access to the Git repository or shared folders rather than a simple web or
app interface.
Real-time updates are delayed because the site must be rebuilt, tested, and
deployed.
Build times can increase rapidly and deployment could become
cumbersome.

Static site generators are perhaps best suited to sites containing no more than a
few hundred pages with a couple of new posts every week. Automated build and
deploy processes will be required, and you may reach a point where a CMS
becomes a more practical option.

7. Server-side Functionality

Static sites are perfect for content pages, but the situation becomes more
challenging when you require user logins, form lling, search facilities, discussion
forums, or other server and database interactivity. Options include:

1. Adding a third-party, client-side component such as Angolia search or


Disqus comments.
2. Creating your own server (or serverless) APIs which can be consumed by
client-side JavaScript to add required features.
3. Generating pages containing <?php ... ?> or similar server-side code
blocks.
4. Switching to a framework such as Next.js, which renders static content
where possible but also allows server-side processing.

However, the development time, build complexity, security implications, testing


effort, and expense will increase. Contrast that to installing a suitable WordPress
plugin which can implement client or server-side functionality within a few
minutes.
Is a Static Site Right for You?

Before making any decision, examine:

Learn PHP for free!


Make the leap into server-side programming with a comprehensive cover
of PHP & MySQL.

Normally RRP $39.99 Yours absolutely free

Name

Email

Get the book free

your project requirements, size, complexity, update frequency, etc.


your users, their location, expectations, etc.
your team’s development skills, and
any hosting and/or deployment factors.

The vast majority of websites rarely exceed a few dozen pages, receive infrequent
updates, and depend on a developer to make those changes. A CMS is often
overkill, so a static site generator could simplify development and reduce costs.
Persuading your client to abandon their content administration panels may be a
tougher task!
For practical demonstrations of building sites with a static site generator, see:

How to Create a Static Site with Metalsmith


Getting Started with Eleventy
How to Use WordPress as a Headless CMS for Eleventy
Form Handling for Jamstack Sites Using Cloud are Workers

Craig Buckler

Craig is a freelance UK web consultant who built his rst page for IE2.0 in 1995. Since that time he's been
advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise
speci cations, websites and online applications for companies and organisations including the UK
Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's
written more than 1,000 articles for SitePoint and you can nd him @craigbuckler.

Latest Remote Jobs

Senior Frontend Engineer


SitePoint
react javascript

.Net Developer
Global Technology
.net sql

Senior Engineer - Data Team


IPinfo
bigquery python

Full Stack Developer


Bottomless

Dev Tools & OSS Architect


Bit
javascript

More Remote Jobs


7 Reasons to Use a Static Site Generator
By Craig Buckler

JavaScript

April 28, 2021

Share:

Static site generators (SSGs) have become increasingly popular over the past
decade. This article discusses how your site could bene t from the developer-
friendly build processes, easier deployments, improved performance, and
better security offered by a static site.

First, let’s establish what we mean by the term “static site generator” …

What is a Static Site?

Think back to the rst website you built. Most developers start by creating a
series of pages contained within individual HTML les. Each will call in assets
such as images, CSS, and perhaps a sprinkling of JavaScript. You possibly
launched these les directly from the le system without a web server. Life was
simple.

Di culties arise as your site becomes larger and more complex. Consider
navigation: it may be similar in every le, but adding a new page requires updates
to every other. Even references to CSS and images can become awkward as
folder structures evolve. You may have considered options such as server-side
includes or PHP, but an easier option can be a content management system
(CMS) …

What is a Content Management System?


A CMS typically provides administrative control panels. These allow authors to
write content that’s stored in a back-end database. When a visitor requests a URL,
the CMS:

1. determines which page is required


2. requests appropriate content from the database
3. loads an HTML template (normally from the le system)
4. renders the content within the template, and
5. returns a formatted HTML page to the visitor’s browser.

This occurs almost instantly. The template can include code to generate menus
according to the navigation hierarchy. Life is sweet, and more than four in ten
people choose the PHP/MySQL-powered, open-source WordPress CMS to
manage their website.

Unfortunately, a CMS raises a different set of issues:

You need to adhere to the CMS’s way of working. It can be awkward to add
custom text or components.
The server is doing more work, and performance can be affected.
There are additional points of failure. A software upgrade or database failure
can bring your site down.

What is a Static Site Generator?

An SSG is a compromise between using a hand-coded static site and a full CMS,
while retaining the bene ts of both. In essence, you generate a static HTML page-
based website using CMS-like concepts such as templates. The content can be
extracted from a database, Markdown les, an API, or any practical storage
location.
The site generation can occur on your development machine, staging server, or
using a service to build when changes are pushed to the code repository. The
resulting HTML les and other assets are then deployed to a live web server.

The term “static” doesn’t mean “unchanging”. An SSG builds a page once, while a
CMS builds it on each request. The end result is identical and users will never
know the difference.

A related concept is a “Headless” or “Decoupled” CMS. These use an interface


such as WordPress to handle content administration but allow other systems to
access the data via a REST API, or a GraphQL API. Therefore, an SSG such as
Eleventy can build a static website using WordPress page content extracted from
an internal server. The resulting HTML les can be uploaded to a web server, but
the WordPress installation need never be publicly accessible from outside the
organization.

The term Jamstack (JavaScript, APIs, and Markup) is also used in relation to
static sites. It refers to the rise in frameworks, serverless functions, and
associated tools which generate static les but allow more complex interactivity
to be created.

Popular static site generators include Jekyll, Eleventy, Gatsby, Hugo, and
Metalsmith. SSGs are available for most languages (see StaticGen for many
more). Frameworks such as Next.js statically render pages where possible, but
also allow the developer to run server-side code when necessary.

Let’s examine the bene ts of using an SSG …

1. Flexibility

CMSs normally constrain your options, because they’re tied to a database with
speci c elds. If you want to add a Twitter widget to some pages, you’ll normally
require a plugin, a shortcode, or some custom functionality.

In a static site, the widget can simply be inserted into a le directly or using a
partial/snippet. There are few limits, because you’re unshackled by the those
imposed by a CMS.

2. Better Performance

Most CMS applications offer built-in or plugin-powered caching systems to


ensure pages are generated and reused when possible. This is effective, although
the overhead of managing, validating, and re-generating cached pages remains.

Static sites can create pre-cached pages which need never expire. Files can also
be mini ed prior to deployment to guarantee the smallest load and easily
deployed via global content delivery networks (CDNs). A static site will always
perform better than a CMS-powered version using a similar template.

Learn PHP for free!


Make the leap into server-side programming with a comprehensive cover
of PHP & MySQL.

Normally RRP $39.99 Yours absolutely free

Name

Email

Get the book free


3. Fewer Server-side Dependencies

A typical WordPress installation requires:

a suitable operating system such as Ubuntu or CentOS


a web server such as Apache or NGINX
PHP with associated extensions and web server con gurations
MySQL
the WordPress application
any necessary plugins
the theme/template code.

These dependencies must be installed and managed. WordPress requires less


effort than some other applications, but it’s still possible for a single update to
cause chaos.

A static site generator may require just as many dependencies, but they can run
on a developer’s PC and are not deployed to a production server. An SSG
generates client-side HTML les and associated assets which can be hosted on
any web server. There’s nothing else to install, manage, or maintain.

4. Improved Reliability

A CMS is complex, with many moving parts and points of failure. Run a
WordPress site for any length of time and you’ll almost certainly encounter the
dreaded “Failed to establish a database connection” error. Unforeseen CMS
problems can arise from sudden tra c surges, which overload the server, crash
the database, or restrict active connections.
Serving a static site is less intensive. In many cases, the server just has to return
at les so scaling according to tra c demand becomes simple. It’s still possible
to crash a web server or overload APIs, but it’ll take considerably more concurrent
requests.

5. Superior Security

There are several reasons why someone may want to attack your website. Tra c
hijacking, rogue advertising, linking, authenticity spoo ng, and malware hosting all
permit an unauthorized user to make monetary and/or kudos gains.

A CMS opens a number of attack vectors. The most obvious is the login screen:
it’s only as secure as the weakest user password. Be aware that any page running
server-side code also offers potential exploits — such as ring spam emails via
your contact form. It may not be obvious that someone has gained access; the
worst culprits want to stay hidden.

A static site may require little or no server-side functionality. Some risks remain,
but they’re rarely as problematic:

Someone could gain access to a server via SSH or FTP and deface pages or
upload les. However, it’s usually simple to check for changes (perhaps
using git status ), wipe the whole site, and regenerate it again.
APIs called by a static site are exposed in the browser and could be exploited
in an identical way to any server-side code — such as a form emailer. Good
security practices, CORS, and CSP will help.

6. Client Control Considerations

You can spend weeks building an attractive CMS theme for the client to trash their
site within minutes of handover! Using a CMS is not necessarily easy, and it offers
considerable power to content editors. You can lock down rights such as plugin
installation, but it won’t prevent someone changing fonts, introducing clashing
colors, adding poor photography, or corrupting the layout.

A static site can be as limited or as exible as you choose. If you’re using


Markdown or similar at les, editors are less able to make mistakes or adversely
affect page styling. Some will miss the CMS content administration panels, but
you can either:

1. use their existing CMS and cleanse data before generation, or


2. provide simpler work ows such as editing Git-based les in StackEdit or
Hackmd.io.

7. Version Control and Testing

Database data is volatile. A CMS permits users to add, delete, or change content
on a whim. Wiping the whole site is a few clicks away. You can back up databases
but, even if that’s done regularly, you’re still likely to lose some data.

A static site is generally safer. Content can be stored in:

at les: they can then be version controlled using Git or similar systems.
Old content is retained, and changes can be undone quickly.
private databases: data is only required when the site is generated so it need
not be exposed on a public server.

Testing also becomes easier because the site can be generated and previewed
anywhere — even on a client’s PC.

With a little more effort, you can implement deployment systems to build the site
remotely and update the live server when new content has been pushed to a
repository, reviewed, and approved.
So all is good in the static site world. Or is it? Read my follow-up post on 7
Reasons NOT to Use a Static Site Generator.

For a practical demonstrations of building sites with a Static Site Generator, see:

How to Create a Static Site with Metalsmith


Getting Started with Eleventy
How to Use WordPress as a Headless CMS for Eleventy

Craig Buckler

Craig is a freelance UK web consultant who built his rst page for IE2.0 in 1995. Since that time he's been
advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise
speci cations, websites and online applications for companies and organisations including the UK
Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's
written more than 1,000 articles for SitePoint and you can nd him @craigbuckler.

Latest Remote Jobs

Senior Frontend Engineer


SitePoint
react javascript

.Net Developer
Global Technology
.net sql

Senior Engineer - Data Team


IPinfo
bigquery python

Full Stack Developer


Bottomless

Dev Tools & OSS Architect


Bit
javascript

More Remote Jobs


How to Use ngrok to Share a Local
Development Site
By Craig Buckler

Web

April 22, 2021

Share:

This tutorial demonstrates a way to share your localhost development server


with anyone, anywhere, using ngrok to create a secure tunnel to your local
machine.

Demonstrating your application’s latest features to project managers or clients


isn’t easy unless they’re sitting a few desks away. It may be possible to commit
the changes and deploy to a public staging server, but that process can be
impractical if you’re just seeking an opinion about a widget color or demonstrating
the futility of their ridiculous suggestion!

Ideally, you need some way to share access to a web application currently running
on your localhost development server. ngrok provides that solution.

What is ngrok?

Your development machine may be connected to a secure network behind a


rewall. To work around access restrictions, ngrok runs a small client process on
your machine which creates a private connection tunnel to the ngrok cloud
service. Your localhost development server is mapped to an ngrok.io
sub-domain, which a remote user can then access. There’s no need to expose
ports, set up forwarding, or make other network changes.
The ngrok client software is available for Windows, macOS, and Linux.

Is ngrok Secure?

The connection tunnel established by ngrok is secure and can only transmit data
to the localhost port you have open. It would be di cult to do any damage,
but ngrok is only as secure as the application you’re testing.

In most cases, you’ll use ngrok to temporarily grant access to someone by issuing
them with a randomly generated URL. It’s best to assume that anyone could
access your app while the tunnel is open. You may want to disable that “delete all
les” option while ngrok is active!

What Does ngrok Cost?

The basic ngrok service is free and permits up to four tunnels and 40 connections
per minute. Commercial options start from $5 per month, providing further
connections and custom domains.

Download ngrok

To start, open ngrok.com in your browser and click Sign up to register. A Google
or GitHub account is easiest, but you can choose standard registration with an
email address and password. An email veri cation link will be sent to you.

After login, you’ll be directed to the ngrok dashboard where you can download the
client for your operating system.
Download and extract the le, following any speci c instructions for your OS. It’s
then necessary to add your authentication token by running the command shown
in the Connect your account section a little further down the page.

./ngrok authtoken <token>

Note: Windows users will enter ./ngrok.exe .

How to Use ngrok

Launch your web application using its normal start command, then note the port
and whether it’s running on http or https . To start a new ngrok tunnel, run:

./ngrok <protocol> <port>

For example, if your site is served on http://localhost:8888 , enter:

./ngrok http 8888

The terminal will clear and show the status with two Forwarding http and
https addresses, such as http://123456789.ngrok.io/ . You can pass
either URL to another person so they can access your application from anywhere.
The terminal shows a log of requests while ngrok is active.
Learn PHP for free!
Make the leap into server-side programming with a comprehensive cover
of PHP & MySQL.

Normally RRP $39.99 Yours absolutely free

Name

Email

Get the book free

The ngrok status panel panel at dashboard.ngrok.com/endpoints/status also


shows a list of currently active URLs and client IP addresses. (You may need to
refresh the browser to update it.)

Once you’ve nished, quit ngrok by pressing Ctrl | Cmd + C in your terminal.
Further help and options are available by entering:

./ngrok help

ngrok Alternatives

ngrok is possibly the easiest and most well-known localhost tunneling


service, but alternative options include:
LocalXpose: a commercial service with free options. Signup is required, but
terminal-based and Graphical User Interface clients are available.

localhost.run: a free service which works via SSH so no client or signup is


necessary.

localtunnel: an open-source Node.js client. No signup is necessary.

JPRQ: an open-source Python client. No signup is necessary.

sish: an open-source, Docker-based container client. No signup is required.

ngrok and similar secure tunnel services can revolutionize how you demonstrate
web apps to other remote workers. It will help testing and reduce frustrating
feedback delays.

Craig Buckler

Craig is a freelance UK web consultant who built his rst page for IE2.0 in 1995. Since that time he's been
advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise
speci cations, websites and online applications for companies and organisations including the UK
Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's
written more than 1,000 articles for SitePoint and you can nd him @craigbuckler.

Latest Remote Jobs

Senior Frontend Engineer


SitePoint
react javascript

.Net Developer
Global Technology
.net sql
. et sq

Senior Engineer - Data Team


IPinfo
bigquery python

Full Stack Developer


Bottomless

Dev Tools & OSS Architect


Bit
javascript

More Remote Jobs

Stuff we do About Contact

Premium Our story Contact us

Newsletters Terms of use FAQ

Forums Privacy policy Publish your book with us

Deals Corporate memberships Write an article for us

Remote Jobs Advertise

Connect

© 2000 – 2021 SitePoint Pty. Ltd.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

You might also like