The JavaScript Developer Tools
The JavaScript Developer Tools
JAVASCRIPT
DEVELOPER
TOOLS
BY FLAVIO COPES
HTTPS://FLAVIOCOPES.COM
Testing
Jest
Package managers
Yarn
npm
Editor tools
ESLint
Prettier
Debugging
Browser DevTools
Console API
What is webpack?
Installing webpack
Global install
Local install
What is webpack?
Webpack is a tool that lets you compile JavaScript modules, also known as
module bundler.
Given a large number of les, it generates a single le (or a few les) that
run your app.
Webpack is not limited to be used on the frontend, but it’s also useful in
backend Node.js development as well.
Grunt
Broccoli
Gulp
There are lots of similarities in what those and Webpack can do, but the
main di erence is that those are known as task runners, while webpack
was born as a module bundler.
It’s a more focused tool: you specify an entry point to your app (it could
even be an HTML le with script tags) and webpack analyzes the les and
bundles in a single JavaScript output le all you need to run the app.
Installing webpack
Webpack can be installed globally or locally for each project.
Global install
Here’s how to install it globally with Yarn:
with npm:
webpack-cli
Local install
Webpack can be installed locally as well. It’s the recommended setup,
because webpack can be updated per-project, and you have less resistance
in using the latest features just for a small project rather than updating all
the projects you have the use webpack.
With Yarn:
with npm:
{
//...
"scripts": {
"build": "webpack"
}
}
yarn build
You can customize every little bit of webpack of course, when you need.
The webpack con guration is stored in the webpack.config.js le, in
the project root folder.
module.exports = {
/*...*/
entry: './index.js'
/*...*/
}
The output
By default the output is generated in ./dist/main.js . This example
puts the output bundle into app.js :
module.exports = {
/*...*/
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
}
/*...*/
}
Loaders
Using webpack allows you to use import or require statements in your
JavaScript code to not just include other JavaScript, but any kind of le, for
example CSS.
Webpack aims to handle all our dependencies, not just JavaScript, and
loaders are one way to do that.
import 'style.css'
module.exports = {
/*...*/
module: {
rules: [
{ test: /\.css$/, use: 'css-loader' },
}]
}
/*...*/
}
The regular expression target any CSS le.
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
}
/*...*/
}
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.css$/,
use:
[
'style-loader',
'css-loader',
]
}
]
}
/*...*/
}
The order matters, and it’s reversed (the last is executed rst).
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
/*...*/
}
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
},
resolve: {
extensions: [
'.js',
'.jsx'
]
}
/*...*/
}
Plugins
Plugins are like loaders, but on steroids. They can do things that loaders
can’t do, and they are the main building block of webpack.
module.exports = {
/*...*/
plugins: [
new CleanWebpackPlugin(['dist']),
]
/*...*/
}
Development mode:
"scripts": {
"build": "webpack"
}
allows us to run webpack by running
or
or simply
yarn build
Watching changes
Webpack can automatically rebuild the bundle when a change in your app
happens, and keep listening for the next change.
"scripts": {
"watch": "webpack --watch"
}
and run
or
yarn run watch
or simply
yarn watch
One nice feature of the watch mode is that the bundle is only changed if
the building has no errors. If there are errors, watch will keep listening for
changes, and try to rebuild the bundle, but the current, working bundle is
not a ected by those problematic builds.
Handling images
Webpack allows to use images in a very convenient way, using the file-
loader (https://webpack.js.org/loaders/ le-loader/) loader.
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
}
/*...*/
}
Allows you to import images in your JavaScript:
file-loader can handle other asset types as well, like fonts, CSV les,
xml, and more.
This example loads any PNG le smaller than 8KB as a data URL.
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.png$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
}
]
}
/*...*/
}
module.exports = {
/*...*/
module: {
rules: [
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}
]
}
/*...*/
}
You tell webpack to generate source maps using the devtool property of
the con guration:
module.exports = {
/*...*/
devtool: 'inline-source-map',
/*...*/
}
Introduction to Babel
Installing Babel
An example Babel con guration
Babel presets
es2015 preset
env preset
react preset
More info on presets
Introduction to Babel
Babel is an awesome tool, and it’s been around for quite some time, but
nowadays almost every JavaScript developer relies on it, and this will
continue going on, because Babel is now indispensable and has solved a
big problem for everyone.
Which problem?
The problem that every Web Developer has surely had: a feature of
JavaScript is available in the latest release of a browser, but not in the older
versions. Or maybe Chrome or Firefox implement it, but Safari iOS and
Edge do not.
Which is now supported by all modern browsers. IE11 does not support it,
nor Opera Mini (How do I know? By checking the ES6 Compatibility Table
(http://kangax.github.io/compat-table/es6/#test-arrow_functions) ).
So how should you deal with this problem? Should you move on and leave
the customers with older/incompatible browsers behind, or should you
write older JavaScript code to make all your users happy?
Enter Babel. Babel is a compiler: it takes code written in one standard, and
it transpiles it to code written into another standard.
You can con gure Babel to transpile modern ES2017 JavaScript into
JavaScript ES5 syntax:
[1, 2, 3].map(function(n) {
return n + 1
})
This must happen at build time, so you must setup a work ow that handles
this for you. Webpack is a common solution.
(P.S. if all this ES thing sounds confusing to you, see more about ES
versions in the ECMAScript guide)
Installing Babel
Babel is easily installed using npm or Yarn:
or
This will make the global babel command available in the command line:
Now inside your project install the babel-core and babel-loader packages,
by running:
or
By default Babel does not provide anything, it’s just a blank box that you
can ll with plugins to solve your speci c needs.
or (Yarn)
{
"plugins": ["transform-es2015-arrow-functions"]
}
TIP: If you have never seen a dot file (a file starting with a dot) it might be
odd at first because that file might not appear in your file manager, as
it’s a hidden file.
var bob = {
_name: "Bob",
_friends: ["Sally", "Tom"],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
};
console.log(bob.printFriends());
var bob = {
_name: "Bob",
_friends: ["Sally", "Tom"],
printFriends() {
var _this = this;
this._friends.forEach(function (f) {
return console.log(_this._name + " knows " + f);
});
}
};
console.log(bob.printFriends());
As you can see arrow functions have all been converted to JavaScript ES5
function s.
Babel presets
We just saw in the previous article how Babel can be con gured to
transpile speci c JavaScript features.
You can add much more plugins, but you can’t add to the con guration
features one by one, it’s not practical.
es2015 preset
This preset provides all the ES2015 features. You install it by running
or
and by adding
{
"presets": ["es2015"]
}
env preset
The env preset is very nice: you tell it which environments you want to
support, and it does everything for you, supporting all modern JavaScript
features.
E.g. “support the last 2 versions of every browser, but for Safari let’s
support all versions since Safari 7`
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}]
]
}
or “I don’t need browsers support, just let me work with Node.js 6.10”
{
"presets": [
["env", {
"targets": {
"node": "6.10"
}
}]
]
}
react preset
The react preset is very convenient when writing React apps, by adding
preset-flow , syntax-jsx , transform-react-jsx , transform-
react-display-name .
By including it, you are all ready to go developing React apps, with JSX
transforms and Flow support.
TIP: read the webpack guide if you’re not familiar with webpack
or
entry: [
'babel-polyfill',
// your app scripts should be here
],
module: {
loaders: [
// Babel loader compiles ES2015 into ES5 for
// complete cross-browser support
{
loader: 'babel-loader',
test: /\.js$/,
// only include files present in the `src` subdirectory
include: [path.resolve(__dirname, "src")],
// exclude node_modules, equivalent to the above line
exclude: /node_modules/,
query: {
// Use the default ES2015 preset
// to include all ES2015 features
presets: ['es2015'],
plugins: ['transform-runtime']
}
}
]
}
By keeping the presets and plugins information inside the
webpack.config.js le, we can avoid having a .babelrc le.
JEST
Jest
Introduction to Jest
Installation
Create the rst Jest test
Run Jest with VS Code
Matchers
Setup
Teardown
Group tests using describe()
Testing asynchronous code
Callbacks
Promises
Async/await
Mocking
Snapshot testing
Introduction to Jest
Jest is a library for testing JavaScript code.
It’s an open source project maintained by Facebook, and it’s especially well
suited for React code testing, although not limited to that: it can test any
JavaScript code. Its strengths are:
it’s fast
it can perform snapshot testing
it’s opinionated, and provides everything out of the box without
requiring you to make choices
In my opinion the biggest feature of Jest is it’s an out of the box solution
that works without having to interact with other testing libraries to perform
its job.
Installation
Jest is automatically installed in create-react-app , so if you use that,
you don’t need to install Jest.
Jest can be installed in any other project using Yarn:
or npm:
{
"scripts": {
"test": "jest"
}
}
so that tests can be run using yarn test or npm run test .
and run all your tests using the jest command line tool.
Create the first Jest test
Projects created with create-react-app have Jest installed and
precon gured out of the box, but adding Jest to any project is as easy as
typing
{
"scripts": {
"test": "jest"
}
}
Now, you don’t have any test here, so nothing is going to be executed:
Let’s create the rst test. Open a math.js le and type a couple functions
that we’ll later test:
Now create a math.test.js le, in the same folder, and there we’ll use
Jest to test the functions de ned in math.js :
Running yarn test results in Jest being run on all the test les it nds,
and returning us the end result:
Once you install it, it will automatically detect if you have installed Jest in
your devDependencies and run the tests. You can also invoke the tests
manually by selecting the Jest: Start Runner command. It will run the tests
and stay in watch mode to re-run them whenever you change one of the
les that have a test (or a test le):
Matchers
In the previous article I used toBe() as the only matcher:
All those matchers can be negated using .not. inside the statement, for
example:
For use with promises, you can use .resolves and .rejects :
expect(Promise.resolve('lemon')).resolves.toBe('lemon')
expect(Promise.reject(new
Error('octopus'))).rejects.toThrow('octopus')
Setup
Before running your tests you will want to perform some initialization.
To do something once before all the tests run, use the beforeAll()
function:
beforeAll(() => {
//do something
})
To perform something before each test runs, use beforeEach() :
beforeEach(() => {
//do something
})
Teardown
Just as you could do with the setup, you can perform something after each
test runs:
afterEach(() => {
//do something
})
afterAll(() => {
//do something
})
Callbacks
You can’t have a test in a callback, because Jest won’t execute it - the
execution of the test le ends before the callback is called. To x this, pass
a parameter to the test function, which you can conveniently call done .
Jest will wait until you call done() before ending that test:
//uppercase.js
function uppercase(str, callback) {
callback(str.toUpperCase())
}
module.exports = uppercase
//uppercase.test.js
const uppercase = require('./src/uppercase')
Promises
With functions that return promises, we simply return a promise from the
test:
//uppercase.js
const uppercase = (str) => {
return new Promise((resolve, reject) => {
if (!str) {
reject('Empty string')
return
}
resolve(str.toUpperCase())
})
}
module.exports = uppercase
//uppercase.test.js
const uppercase = require('./uppercase')
test(`uppercase 'test' to equal 'TEST'`, () => {
return uppercase('test').then(str => {
expect(str).toBe('TEST')
})
})
Promises that are rejected can be tested using .catch() :
//uppercase.js
const uppercase = (str) => {
return new Promise((resolve, reject) => {
if (!str) {
reject('Empty string')
return
}
resolve(str.toUpperCase())
})
}
module.exports = uppercase
//uppercase.test.js
const uppercase = require('./uppercase')
//uppercase.test.js
const uppercase = require('./uppercase')
test(`uppercase 'test' to equal 'TEST'`, async () => {
const str = await uppercase('test')
expect(str).toBe('TEST')
})
Mocking
In testing, mocking allows you to test functionality that depends on:
Database
Network requests
access to Files
any External system
so that:
Mocking is useful when you want to avoid side e ects (e.g. writing to a
database) or you want to skip slow portions of code (like network access),
and also avoids implications with running your tests multiple times (e.g.
imagine a function that sends an email or calls a rate-limited API).
Even more important, if you are writing a Unit Test, you should test the
functionality of a function in isolation, not with all its baggage of things it
touches.
Using mocks, you can inspect if a module function has been called and
which parameters were used, with:
expect().toHaveBeenCalled() : check if a spied function has been
called
expect().toHaveBeenCalledTimes() : count how many times a
spied function has been called
expect().toHaveBeenCalledWith() : check if the function has
been called with a speci c set of parameters
expect().toHaveBeenLastCalledWith() : check the parameters
of the last time the function has been invoked
Example:
expect(mathjs.log).toHaveBeenCalled()
expect(mathjs.log).toHaveBeenCalledWith(10000, 10)
})
module.exports = {
log: jest.fn(() => 'test')
}
This will mock the log() function of the package. Add as many functions as
you want to mock:
Pre-built mocks
You can nd pre-made mocks for popular libraries. For example this
package https://github.com/je au/jest-fetch-mock allows you to mock
fetch() calls, and provide sample return values without interacting with
the actual server in your tests.
Snapshot testing
Snapshot testing is a pretty cool feature o ered by Jest. It can memorize
how your UI components are rendered, and compare it to the current test,
raising an error if there’s a mismatch.
the rst time you run this test, Jest saves the snapshot to the
__snapshots__ folder. Here’s what App.test.js.snap contains:
As you see it’s the code that the App component renders, nothing more.
The next time the test compares the output of <App /> to this. If App
changes, you get an error:
Watch Usage
› Press u to update failing snapshots.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
If your change is intended, pressing u will update the failing snapshots,
and make the test pass.
You can also update the snapshot by running jest -u (or jest --
updateSnapshot ) outside of watch mode.
YARN
Yarn is a JavaScript Package Manager, a direct competitor of
npm, one of Facebook most popular Open Source projects
Intro to Yarn
Install Yarn
Managing packages
Inspecing licenses
Inspecting dependencies
Upgrading packages
Intro to Yarn
Yarn is a JavaScript Package Manager, a direct competitor of npm, and it’s
one of Facebook most popular Open Source projects.
It’s compatible with npm packages, so it has the great advantage of
being a drop-in replacement for npm.
The reason you might want to use Yarn over npm are: - faster download of
packages, which are installed in parallel - support for multiple registries -
o ine installation support
This is not the only feature, many other goodies are provided by Yarn,
which we’ll see in this article.
Tools eventually converge to a set of features that keeps them on the same
level to stay relevant, so we’ll likely see those features in npm in the future
- competition is nice for us users.
Install Yarn
While there is a joke around about installing Yarn with npm ( npm install
-g yarn ), it’s not recommended by the Yarn team.
but every Operating System has its own package manager of choice that
will make the process very smooth.
In the end, you’ll end up with the yarn command available in your shell:
Managing packages
Yarn writes its dependencies to a le named package.json , which sits in
the root folder of your project, and stores the dependencies les into the
node_modules folder, just like npm if you used it in the past.
yarn
or
yarn install
Remove a package
yarn remove package-name
Inspecing licenses
When installing many dependencies, which in turn might have lots of
depencencies, you install a number of packages, of which you don’t have
any idea about the license they use.
Yarn provides a handy tool that prints the licens of any dependency you
have:
yarn licenses ls
and it can also generate a disclaimer automatically including all the
licenses of the projects you use:
Upgrading packages
If you want to upgrade a single package, run
yarn upgrade
But this command can sometimes lead to problems, because you’re blindly
upgrading all the dependencies without worrying about major version
changes.
Yarn has a great tool to selectively update packages in your project, which
is a huge help for this scenario:
yarn upgrade-interactive
NPM
Introduction to npm
Downloads
Versioning
Running Tasks
Introduction to npm
npm means node package manager.
In January 2017 over 350000 packages were reported being listed in the
npm registry, making it the biggest single language code repository on
Earth, and you can be sure there is a package for (almost!) everything.
Downloads
npm manages downloads of dependencies of your project.
npm install
it will install everything the project needs, in the node_modules folder,
creating it if it’s not existing already.
Updating packages
Updating is also made easy, by running
npm update
npm will check all packages for a newer version that satis es your
versioning constrains.
You can specify a single package to update as well:
Versioning
In addition to plain downloads, npm also manages versioning, so you can
specify any speci c version of a package, or require a version higher or
lower than what you need.
Many times you’ll nd that a library is only compatible with a major release
of another library.
In all those cases, versioning helps a lot, and npm follows the Semantic
Versioning (SEMVER) standard.
Running Tasks
The package.json le supports a format for specifying command line tasks
that can be run by using
npm <task-name>
For example:
{
"scripts": {
"start-dev": "node lib/server-development",
"start": "node lib/server-production"
},
}
{
"scripts": {
"watch": "webpack --watch --progress --colors --config
webpack.conf.js",
"dev": "webpack --progress --colors --config webpack.conf.js",
"prod": "NODE_ENV=production webpack -p --config
webpack.conf.js",
},
}
$ npm watch
$ npm dev
$ npm prod
ESLINT
Learn the basics of the most popular JavaScript linter, which
can help to make your code adhere to a certain set of
syntax conventions, check if the code contains possible
sources of problems and if the code matches a set of
standards you or your team de ne
What is linter?
ESLint
Install ESLint globally
Install ESLint locally
Use ESLint in your favourite editor
Common ESLint con gurations
Running a linter against your code can tell you many things:
It will raise warnings that you, or your tools, can analyze and give you
actionable data to improve your code.
ESLint
ESLint is a linter for the JavaScript programming language, written in
Node.js.
ESLint will help you catch those errors. Which errors in particular you ask?
ESLint is very exible and con gurable, and you can choose which rules
you want to check for, or which kind of style you want to enforce. Many of
the available rules are disabled and you can turn them on in your
.eslintrc con guration le, which can be global or speci c to your
project.
Run
or
{
"extends": "airbnb",
}
React
Linting React code is easy with the React plugin:
or
{
"extends": "airbnb",
"plugins": [
"react"
],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
}
}
}
Use a specific version of ECMAScript
ECMAScript changes version every year now.
{
"parserOptions": {
"ecmaVersion": 6,
}
}
{
"parserOptions": {
"ecmaFeatures": {
"impliedStrict": true
}
}
}
/* eslint-disable */
alert('test');
/* eslint-enable */
or on a single line:
alert('test'); // eslint-disable-line
Introduction to Prettier
Less options
Di erence with ESLint
Installation
Prettier for beginners
Introduction to Prettier
Prettier is an opinionated code formatter.
JavaScript
Flow, TypeScript
CSS, SCSS, Less
JSX
GraphQL
JSON
Markdown
The most important links you need to know more about Prettier are
https://prettier.io/
https://github.com/prettier/prettier
https://www.npmjs.com/package/prettier
Less options
I learned Go recently and one of the best things about Go is gofmt, an
o cial tool that automatically formats your code according to common
standards.
95% (made up stat) of the Go code around looks exactly the same, because
this tool can be easily enforced and since the style is de ned on you by the
Go maintainers, you are much more likely to adapt to that standard
instead of insisting on your own style. Like tabs vs spaces, or where to put
an opening bracket.
This might sound like a limitation, but it’s actually very powerful. All Go
code looks the same.
ESLint also highlights formatting issues, but since it’s a lot con gurable,
everyone could have a di erent set of formatting rules. Prettier provides a
common ground for all.
and some others, but Prettier tries to keep the number of those
customizations under control, to avoid becoming too customizable.
Installation
Prettier can run from the command line, and you can install it using Yarn or
npm.
Another great use case for Prettier is to run it on PRs for your Git
repositories, for example on GitHub.
If you use a supported editor the best thing is to use Prettier directly from
the editor, and the Prettier formatting will be run every time you save.
Also, even if you started using JavaScript 2 weeks ago, with Prettier your
code - style wise - will look just like code written from a JavaScript Guru
writing JS since 1998.
GIT
Git is a free and Open Source *version control system*
(VCS), a technology used to track older versions of les,
providing the ability to roll back and maintain separate
di erent versions at the same time
What is Git
Distributed VCS
Installing Git
OSX
Windows
Linux
Initializing a repository
Adding les to a repository
Commit changes
Branches
Push and pull
Add a remote
Push
Pull
Con icts
GitHub Desktop
Tower
GitKraken
Git is a successor of SVN and CVS, two very popular version control
systems of the past. First developed by Linus Torvalds (the creator of
Linux), today is the go-to system which you can’t avoid if you make use of
Open Source software.
Distributed VCS
Git is a distributed system. Many developers can clone a repository from a
central location, work independently on some portion of code, and then
commit the changes back to the central location where everybody updates.
A very popular service that hosts Git repositories is GitHub, especially for
Open Source software, but we can also mention BitBucket, GitLab and
many others which are widely used by teams all over the world to host
their code publicly and also privately.
Installing Git
Installing Git is quite easy on all platforms:
OSX
Using Homebrew (http://brew.sh/) , run:
Windows
Download and install Git for Windows (https://git-for-windows.github.io/) .
Linux
Use the package manager of your distribution to install Git. E.g.
or
git init
What does this command do? It creates a .git folder in the folder where
you ran it. If you don’t see it, it’s because it’s a hidden folder, so it might not
be shown everywhere, unless you set your tools to show hidden folders.
Anything related to Git in your newly created repository will be stored into
this .git directory, all except the .gitignore le, which I’ll talk about in
the next article.
to create a le. The le is now in the directory, but Git was not told to add it
to its index, as you can see what git status tells us:
Commit changes
Once you have one or more changes to the staging area, you can commit
them using
and permanently stores the edit you made into a record store, which you
can inspect by typing git log :
Branches
When you commit a le to Git, you are committing it into the current
branch.
Git is very exible: you can have an inde nite number of branches active at
the same time, and they can be developed independently until you want to
merge one of them into another.
Git by default creates a branch called master . It’s not special in any way
other than it’s the one created initially.
As you can see, git branch lists the branches that the repository has.
The asterisk indicates the current branch.
When creating the new branch, that branch points to the latest commit
made on the current branch. If you switch to it (using git checkout
develop ) and run git log , you’ll see the same log as the branch that
you were previously.
Before you can play with push and pull, however, you need to add a
remote!
Add a remote
A remote is a clone of your repository, positioned on another machine.
I’ll do an example with GitHub. If you have an existing repository, you can
publish it on GitHub. The procedure involves creating a repository on the
platform, through their web interface, then you add that repository as a
remote, and you push your code there.
You specify origin as the remote, because you can technically have more
than one remote. That is the name of the one we added previously, and it’s
a convention.
Pull
The same syntax applies to pulling:
tells Git to push the master branch from origin , and merge it in the
current local branch.
Conflicts
In both push and pull there is a problem to consider: if the remote contains
changes incompatible with your set of commits, the operation will fail.
This happens when the remote contains changes subsequent to your latest
pull, which a ects lines of code you worked on as well.
In the case of push this is usually solved by pulling changes, analyzing the
con icts, and then making a new commit that solves them.
In the case of pull, your working copy will automatically be edited with the
con icting changes, and you need to solve them, and make a new commit
so the codebase now includes the problematic changes that were made on
the remote.
This was key to introduce you to how Git actually works, but in the day-to-
day operations, you are most likely to use an app that exposes you those
commands via a nice UI, although many developers I know like to use the
CLI.
That said, there are many very nice apps that are made to simplify the life
of a developer that turn out very useful especially when you dive more into
the complexity of a Git repository. The easy steps are easy everywhere, but
things could quickly grow to a point where you might nd it hard to use the
CLI.
Some of the most popular apps are
GitHub Desktop
https://desktop.github.com
Free, at the time of writing only available for Mac and Win
Tower
https://www.git-tower.com
Paid, at the time of writing only available for Mac and Win
GitKraken
https://www.gitkraken.com
Free / Paid depending on the needs, for Mac, Win and Linux
Hotfix
If something on our production server requires immediate action, like a
bug x I need to get solved ASAP, I do a short hot x branch, x the thing,
test the branch locally and on a test machine, then merge it to master and
develop.
Every time develop or another hot x branch is merged into master, I tag it
with a version number, and if on GitHub I also create a release, so it’s
easy to move back to a previous state if something goes wrong.
GITHUB
GitHub is a website where millions of developers gather
every day to collaborate on open source software. It's also
the place that hosts billions of lines of code, and also a
place where users of software go to report issues they
might have. Learn all the most important pieces of GitHub
that you should know as a developer
Introduction to GitHub
Why GitHub?
GitHub issues
Social coding
Follow
Stars
Fork
Popular = better
Pull requests
Project management
Comparing commits
Webhooks and Services
Webhooks
Services
Final words
Introduction to GitHub
GitHub is a website where millions of developers gather every day to
collaborate on open source software. It’s also the place that hosts billions
of lines of code, and also a place where users of software go to report
issues they might have.
In short, it’s a platform for software developers, and it’s built around Git.
TIP: If you don’t know about Git yet, checkout the Git guide.
As a developer you can’t avoid using GitHub daily, either to host your
code or to make use of other people’s code. This post explains you some
key concepts of GitHub, and how to use some of its features that improve
your work ow, and how to integrate other applications into your process.
Why GitHub?
Now that you know what GitHub is, you might ask why you should use it.
Major codebases migrated over time to Git from other version control
systems, because of its convenience, and GitHub was historically well
positioned into (and put a lot of e ort to “win”) the Open Source
community.
So today any time you look up some library, you will 99% of the times nd
it on GitHub.
Apart from Open Source code, many developers also host private
repositories on GitHub because of the convenience of a unique platform.
GitHub issues
GitHub issues are one of the most popular bug tracker in the world.
It provides the owners of a repository the ability to organize, tag and assign
to milestones issues.
Sometimes you’ll get a de nitive answer, other times the issue will be left
open and tagged with some information that categorizes it, and the
developer could get back to it to x a problem or improve the codebase
with your feedback.
Most developers are not paid to support their code released on GitHub, so
you can’t expect prompt replies, but other times Open Source repositories
are published by companies that either provide services around that code,
or have commercial o erings for versions with more features, or a plugin-
based architecture, in which case they might be working on the open
source software as paid developers.
Social coding
Some years ago the GitHub logo included the “social coding” tagline.
What did this mean, and is that still relevant? It certainly is.
Follow
With GitHub you can follow developers, by going on their pro le and
clicking “follow”.
In both cases the activity will show up in your dashboard. You don’t follow
like in Twitter, where you see what people say, but you see what people
do.
Stars
One big feat of GitHub is the ability to star a repository. This action will
include it in your “starred repositories” list, which allows you to nd things
you found interesting before, and it’s also one of the most important rating
mechanisms, as the more stars a repo has, the more important it is, and
the more it will show up in search results.
Getting into those trending lists can cause other network e ects like being
featured on other sites, just because you have more visibility.
Fork
The last important network indicator of a project is the number of forks.
This is key to how GitHub works, as a fork is the base of a Pull Request (PR),
a change proposal. Starting from your repository, a person forks it, makes
some changes, then creates a PR to ask you to merge those changes.
Sometimes the person that forks never asks you to merge anything, just
because they liked your code and decided to add something on top of it, or
they xed some bug they were experiencing.
A fork clones the les of a GitHub project, but not any of the stars or issues
of the original project.
Popular = better
All in all, those are all key indicators of the popularity of a project, and
generally along with the date of the latest commit and the involvement of
the author in the issues tracker, is a useful indication of whether or not you
should rely on a library or software.
Pull requests
Before I introduced what is a Pull Request (PR)
Starting from your repository, a person forks it, makes some changes, then
creates a PR to ask you to merge those changes.
This is to say that not always a PR gets accepted fast, and also there is
no guarantee that the PR will even get accepted.
In the example i posted above, there is a PR in the repo that dates back 1.5
years. And this happens in all the projects.
Project management
Along with issues, which are the place where developers get feedback from
users, the GitHub interface o ers other features aimed at helping project
management.
One of those is Projects. It’s very new in the ecosystem and very rarely
used, but it’s a kanban board that helps organizing issues and work that
needs to be done.
While a Git tag can be created programmatically (e.g. using the Command
Line git program), creating a GitHub release is a manual process that
happens through the GitHub UI. You basically tell GitHub to create a new
release and tell them which tag you want to apply that release to.
Comparing commits
GitHub o ers many tools to work with your code.
One of the most important things you might want to do is compare one
branch to another one. Or, compare the latest commit with the version you
are currently using, to see which changes were made over time.
GitHub allows you to do this with the compare view, just add /compare
to the repo name, for example:
https://github.com/facebook/react/compare
For example here I choose to compare the latest React v15.x to the latest
v16.0.0-rc version available at the time of writing, to check what’s changed:
The view shows you the commits made between two releases (or tags or
commits references) and the actual diff, if the number of changes is
lower than a reasonable amount.
When an event happens, GitHub sends a POST request to the URL we told
it to use.
We push to GitHub, GitHub tells the server we pushed, the server pulls
from GitHub.
Services
GitHub services, and the new GitHub apps, are 3rd part integrations that
improve the developer experience or provide a service to you.
For example you can setup a test runner to run the tests automatically
every time you push some new commits, using TravisCI (https://travis-
ci.org/) .
Final words
GitHub is an amazing tool and service to take advantage of, a real gem in
today’s developer toolset. This tutorial will help you start, but the real
experience of working on GitHub on open source (or closed source)
projects is something not to be missed.
BROWSER DEV TOOLS
The Browser DevTools are a fundamental element in the
frontend developer toolbox, and they are available in all
modern browsers. Discover the basics of what they can do
for you
The Console
The emulator
The network panel
JavaScript debugger
Application and Storage
Storage
Application
Security tab
Audits
Once you gured out the di erences between Internet Explored and
Netscape Navigator, and avoided the proprietary tags and technology, all
you had to use was HTML and later CSS.
JavaScript was a tech for creating dialog boxes and a little bit more, but was
de nitely not as pervasive as today.
Although lots of web pages are still plain HTML + CSS, like this page, many
other websites are real applications that run in the browser.
Just providing the source of the page, like browser did once upon a time,
was not enough.
Browser had to provide much more information on how they rendered the
page, and what the page is currently doing, hence they introduced a
feature for developers: their developer tools.
Every browser is di erent and so their dev tools are slightly di erent. At
the time of writing my favorite developer tools are provided by Chrome,
and this is the browser we’ll talk here, although also Firefox and Edge have
great tools as well. I will soon add coverage of the Firefox DevTools.
Hovering the elements in the HTML panel highlights the element in the
page, and clicking the rst icon in the toolbar allows you to click an element
in the page, and analyze it in the inspector.
You can drag and drop elements in the inspector to live change their
positioning in the page.
In addition to editing and disabling properties, you can add a new CSS
property, with any target you want, by clicking the + icon.
Also you can trigger a state for the selected element, so you can see the
styles applied when it’s active, hovered, on focus.
At the bottom, the box model of the selected element helps you gure out
margins, paddings, border and dimensions at a quick glance:
The Console
The second most important element of the DevTools is the Console.
The Console can be seen on its own panel, or by pressing Esc in the
Elements panel, it will show up in the bottom.
The Console serves mainly two purposes: executing custom JavaScript and
error reporting.
alert('test')
You can write more than one line with shift-enter . Pressing enter at
the end of the script runs it.
Error reporting
Any error, warning or information that happens while rendering the page,
and subsequently executing the JavaScript, is listed here.
For example failing to load a resource from the network, with information
on why, is reported in the console.
In this case, clicking the resource URL brings you to the Network panel,
showing more info which you can use to determine the cause of the
problem.
You can lter those messages by level (Error / Warning / Info) and also lter
them by content.
The emulator
The Chrome DevTools embed a very useful device emulator which you can
use to visualize your page in every device size you want.
You can choose from the presets the most popular mobile devices,
including iPhones, iPads, Android devices and much more, or specify the
pixel dimensions yourself, and the screen de nition (1x, 2x retina, 3x retina
HD).
In the same panel you can setup network throttling for that speci c
Chrome tab, to emulate a low speed connection and see how the page
loads, and the “show media queries” option shows you how media
queries modify the CSS of the page.
A very useful option in the toolbar is preserve log. By enabling it, you can
move to another page, and the logs will not be cleared.
Another very useful tool to track loading time is disable cache. This can be
enabled globally in the DevTools settings as well, to always disable cache
when DevTools is open.
Clicking a speci c request in the list shows up the detail panel, with HTTP
Headers report:
Storage
You gain access to detailed reports and tools to interact with the
application storage:
Local Storage
Session Storage
IndexedDb
Web SQL
Cookies
and you can quickly wipe any information, to start with a clean slate.
Application
This tab also gives you tools to inspect and debug Progressive Web Apps.
Click manifest to get information about the web app manifest, used to
allow mobile users to add the app to their home, and simulate the “add to
homescreen” events.
Service workers let you inspect your application service workers. If you
don’t know what service workers are, in short they are a fundamental
technology that powers modern web apps, to provide features like
noti cation, capability to run o ine and synchronize across devices.
Security tab
The Security tab gives you all the information that the browser has
relatively to the security of the connection to the website.
If there is any problem with the HTTPS connection, if the site is served over
SSL, it will provide you more information about what’s causing it.
Audits
The Audits tab will help you nd and solve some issues relative to
performance and in general the quality of the experience that users have
when accessing your website.
You can perform various kinds of audits depending on the kind of website:
The audit is provided by Lighthouse
(https://developers.google.com/web/tools/lighthouse/) , an open source
automated website quality check tool. It takes a while to run, then it
provides you a very nice report with key actions to check.
If you want to know more about the Chrome DevTools, check out this
Chrome DevTools Tips list
THE CONSOLE API
Every browser exposes a console that lets you interact with
the Web Platform APIs and also gives you an inside look at
the code by printing messages that are generated by your
JavaScript code running in the page
Every browser exposes a console that lets you interact with the Web
Platform APIs and also gives you an inside look at the code by printing
messages that are generated by your JavaScript code running in the page.
You can also choose to hide network-generated messages, and just focus
on the JavaScript log messages.
The console is not just a place where you can see messages, but also the
best way to interact with JavaScript code, and many times the DOM. Or,
just get information from the page.
Let’s type our rst message. Notice the >, let’s click there and type
console.log('test')
console.log('test1', 'test2')
For example:
Example:
The third way is through a keyboard shortcut, and it’s cmd-k (mac) or
ctrl + l (Win)
Counting elements
console.count() is a handy method.
const x = 1
const y = 2
const z = 3
console.count("The value of x is " + x + " and has been checked ..
how many times?")
console.count("The value of x is " + x + " and has been checked ..
how many times?")
console.count("The value of y is " + y + " and has been checked ..
how many times?")
What happens is that count will count the number of times a string is
printed, and print the count next to it:
You can just count apples and oranges:
console.log([1, 2])
console.dir([1, 2])
console.log("%O", [1,2])
Which one to use depends on what you need to debug of course, and one
of the two can do the best job for you.
We just need to pass it an array of elements, and it will print each array
item in a new row.
For example
const shoppingCart = {}
shoppingCart.firstItem = {'color': 'black', 'size': 'L'}
shoppingCart.secondItem = {'color': 'red', 'size': 'L'}
shoppingCart.thirdItem = {'color': 'white', 'size': 'M'}
console.table(shoppingCart, ["color", "size"])
Logging different error levels
As we saw console.log is great for printing messages in the Console.
We’ll now discover three more handy methods that will help us debug,
because they implicitly indicate various levels of error.
First, console.info()
As you can see a little ‘i’ is printed beside it, making it clear the log message
is just an information.
Second, console.warn()
this is a bit di erent than the others because in addition to printing a red X
which clearly states there’s an error, we have the full stack trace of the
function that generated the error, so we can go and try to x it.
To limit this problem the Console API o ers a handy feature: Grouping the
Console messages.
You can do the same, but output a collapsed message that you can open
on demand, to further limit the noise:
The nice thing is that those groups can be nested, so you can end up doing
console.group("Main")
console.log("Test")
console.group("1")
console.log("1 text")
console.group("1a")
console.log("1a text")
console.groupEnd()
console.groupCollapsed("1b")
console.log("1b text")
console.groupEnd()
console.groupEnd()
You can start that manually, but the most accurate way to do so is to wrap
what you want to monitor between the profile() and profileEnd()
commands. They are similar to time() and timeEnd() , except they
don’t just measure time, but create a more detailed report.
Here is an example project I made on Glitch with React and React Router:
https://glitch.com/edit/#!/ aviocopes-react-router-v4
With Glitch you can easily create demos and prototypes of applications
written in JavaScript, from simple web pages to advanced frameworks such
as React or Vue, and server-side Node.js apps.
It is built on top of Node, and you have the ability to install any npm
package you want, run webpack and much more.
It’s brought to you by the people that made some hugely successful
products, including Trello and Stack Over ow, so it has a lot of credibility
bonuses for that.
You have access to logs, the console, and lots of internal stu .
You can start diving into the code without losing time setting up an
environment, version control, and focus on the idea, with an automatic
HTTPS URL and a CDN for the media assets.
Also, there’s no lock-in at all, it’s just Node.js (or if you don’t use server-side
JavaScript, it’s just HTML, JS and CSS)
Is it free?
Yes, it’s free, and in the future they might add even more features on top
for a paid plan, but they state that the current Glitch will always be free as
it is now.
You have 128MB of space, excluding npm packages, plus 512MB for
media assets
You can serve up to 4000 requests per hour
Apps are stopped if not accessed for 5 minutes and they do not
receive any HTTP request, and long running apps are stopped after 12
hours. As soon as an HTTP request comes in, they start again
An overview of Glitch
This is the Glitch homepage, it shows a few projects that they decided to
showcase because they are cool, and some starter projects:
Creating an account is free and easy, just press “Sign in” and choose
between Facebook and GitHub as your “entry points” (I recommend
GitHub):
You are redirected to GitHub to authorize:
Once logged in, the home page changes to also show your projects:
Clicking Your Projects sends you to your pro le page, which has your
name in the URL. Mine is https://glitch.com/@ aviocopes.
You can pin projects, to nd them more easily when you’ll have lots of
them.
You can remix a project you like, maybe one you found on Twitter or
featured in the Glitch homepage, or you can start from a project that’s a
boilerplate to start something:
If you’re learning to code right now, the Learn to Code glitch Collection
(https://glitch.com/learn-to-code) is very nice.
I have created a few starter apps that I constantly use for my demos and
tests, and they are:
Glitch makes it very easy to create your own building blocks, and by
pinning them in your pro le, you can have them always on the top, easy to
nd.
Remix a glitch
Once you have a glitch you want to build upon, you just click it, and a
window shows up:
Preview a glitch is code that does something. This shows the result of
the glitch.
Edit Project shows the source of the project, and you can start editing
it
Remix This clones the glitch to a new one
Every time you remix a glitch, a new project is created, with a random
name.
Glitch gave it the name guttural-noodle . Clicking the name you can
change it:
You can also change the description.
From here you can also create a new glitch from zero, remix the current
glitch, or go to another one.
GitHub import/export
There is an easy import/export from/to GitHub, which is very convenient:
Keep your project private
Clicking the lock makes the glitch private:
Create a new project
Clicking “New Project” shows 3 options:
node-app
node-sqlite
webpage
This is a shortcut to going out to nd those starter apps, and remix them.
Under the hoods, clicking one of those options remixes an existing glitch.
On any glitch, clicking “Show” will open a new tab where the app is run:
App URL
Notice the URL, it’s:
https://flavio-my-nice-project.glitch.me
https://glitch.com/edit/#!/flavio-my-nice-project
Noticed the shes on the right of the page? It’s a little JavaScript that Glitch
recommend to add to the page, to let other people remix the project or see
the source:
Running the app
Any time you make a change to the source, the app is rebuilt, and the live
view is refreshed.
Secrets
You don’t want any API key or password that might be used in the code to
be seen by everyone. Any of those secret strings must be put in the special
.env le, which has a key next to it.
If you invite collaborators, they will be able to see the content, as they are
part of the project.
But anyone remixing it, or people invited by you to help, will not see the le
content.
Managing files
Adding a new le to a project is easy.
You can drag and drop files and folders from your local computer, or
click the “New File” button above the les list.
Glitch makes it super easy to add a license, in the New File panel:
Add a license
View the license
The code of conduct is another very important piece for any project and
community. It makes contributors feel welcomed and protected in their
participation to the community.
The Add Code of Conduct button adds a sample code of conduct for open
source projects you can start from.
Click the Add Package button that now appears on top, and you can add
new package.
Also, if you have a package that needs to be updated, Glitch will show the
number of packages that need an update, and you can update them to the
latest release with a simple click:
Update dependencies
Use a custom version of Node.js
You can set the Node.js version to any of these
(https://nodeversions.glitch.me/) in your package.json . Using .x will
use the latest release of a major version, which is the most useful thing,
like this:
{
//...
"engines": {
"node": "8.x"
}
}
Storage
Glitch has a persistent le system. Files are kept on disk even if your app is
stopped, or you don’t use if for a long time.
This allows you to store data on disk, using local databases or le-based
storage ( at- le).
If you put your data in the .data folder, this special name indicates the
content will not be copied to a new project with the glitch is remixed.
Click Share and Embed Project to open the Embed Project view. From
there you can choose to only embed the code, the app, or customize the
height of the widget - and get its HTML code to put on your site:
Embed glitch
Collaborating on a glitch
From the Share panel, the Invite Collaborators to edit link lets you invite
anyone to edit the glitch in real time with you.
You can see their changes as they make it. It’s pretty cool!
When a person jumps in to help, they see the line you highlighted, and I
found that comments made a good way to communicate like a chat:
The debugger
It’s a lot like how Git works - in fact, under the hoods it’s Git powering this
really easy to use interface, which opens clicking the ⏪ button:
How is Glitch different than Codepen or
JSFiddle?
One big di erence that separates Glitch from other tools is the ability to
run server-side code.
Codepen and JSFiddle can only run frontend code, while a Glitch can even
be used as a lightweight server for your apps - keeping the usage limits in
mind.
For example I have set up an Express.js server that is triggered by a
Webhook at speci c times during the day to perform some duties. I don’t
need to worry about it running on another server, I just wrote it on Glitch
and run directly from there.
That’s it!
I hope you like my small tutorial on using Glitch, and I hope I explained
most of the killer features of it.
More questions?
I suggest to just try it, and see if it clicks for you too.
Have fun!
AIRTABLE API FOR
DEVELOPERS
Airtable is an amazing tool. Discover why it's great for any
developer to know about it and its API
A great API
Airtable has an absolutely nice API to work with, which makes it easy to
interface with your Airtable database programmatically.
The API has a limit of 5 requests per second, which is not high, but still
reasonable to work with for most scenarios.
A great documentation for the API
As developers we spend a lot of time reading through docs and trying to
gure out how things work.
An API is tricky because you need to interact with a service, and you want
to both learn what the service exposes, and how can you use the API to do
what you need.
Airtable raises the bar for any API documentation out there. It puts your
API keys, base IDs and table names directly in the examples, so you just
need to copy and paste them into your codebase and you’re ready to go.
Not just that, the examples in the API docs use the actual data in your
table. In this image, notice how the elds example values are actual values
I put in my table:
The API documentation o ers examples using curl :
It’s convenient because it o ers a built-in logic to handle rate limits and
retrying the requests when you exceed them.
Let’s see a few common operations you can perform with the API, but rst
let’s de ne a couple values we’ll reference in the code:
A base is a short term for database, and it can contain many tables.
A table has one or more views that organize the same data in a di erent
way. There’s always at least one view (see more on views
(https://support.airtable.com/hc/en-us/articles/202624989-Guide-to-views)
)
Authenticate
You can set up the AIRTABLE_API_KEY environment variable, and
Airbase.js will automatically use that, or explicitly add it into your code:
Airtable.configure({
apiKey: API_KEY
})
Initialize a base
Reference a table
With a base object, you can now reference a table using
table.select({
view: VIEW_NAME
}).firstPage((err, records) => {
if (err) {
console.error(err)
return
}
If you have (or expect) more than 100 records, you need to paginate
through them, using the eachPage method:
let records = []
table.select({
view: VIEW_NAME
}).eachPage(processPage, processRecords)
record.id
//or
record.getId()
record.createdTime
and you can get any of its properties, which you access through the column
name:
record.get('Title')
record.get('Description')
record.get('Date')
table.create({
"Title": "Tutorial: create a Spreadsheet using React",
"Link": "https://flaviocopes.com/react-spreadsheet/",
}, (err, record) => {
if (err) {
console.error(err)
return
}
console.log(record.getId())
})
Update a record
You can update a single eld of a record, and leave the other elds
untouched, using update :
table.update(record_id, {
"Title": "The modified title"
}, (err, record) => {
if (err) {
console.error(err)
return
}
console.log(record.get('Title'))
})
Or, you can update some elds in a record and clear out the ones you did
not touch, with replace :
table.replace(record_id, {
"Title": "The modified title",
"Description": "Another description"
}, (err, record) => {
if (err) {
console.error(err)
return
}
console.log(record)
})
Delete a record
A record can be deleted using
Introducing Netlify
Netlify and Hugo
Advanced functionality o ered by Netlify for Static Sites
Previewing branches
I did so while my previous hosting was having some issues that made my
site unreachable for a few hours, and while I waited for it to get up online
again, I created a replica of my site on Netlify.
Netlify Logo
Introducing Netlify
There are a few things that made a great impression to me before trying it.
First, the free plan is very generous for free or commercial projects, with
100GB of free monthly bandwidth, and for a static site with just a few
images here and there, it’s a lot of space!
They include a global CDN, to make sure speed is not a concern even in
continents far away from the central location servers.
You can point your DNS nameservers to Netlify and they will handle
everything for you with a very nice interface to set up advanced needs.
To generate the static site, I have to run hugo , and this creates a series of
les in the public/ folder.
I followed this method on Firebase: I ran hugo to create the les, then
firebase deploy , con gured to push my public/ folder content to
the Google servers.
If you think this is nothing new, you’re right, since this is not hard to
implement on your own server (I do so on other sites not hosted on
Netlify), but here’s something new: you can preview any GitHub (or GitLab,
or BitBucket) branch / PR on a separate URL, all while your main site is live
and running with the “stable” content.
Another cool feature is the ability to perform A/B testing on 2 di erent Git
branches.
This is an advantage (less security issues to care about) but also a limitation
in the functionality you can implement.
A blog is nothing complex, maybe you want to add comments and they can
be done using services like Disqus or others.
Or maybe you want to add a form and you do so by embedding forms
generated on 3rd part applications, like Wufoo or Google Forms.
I just scratched the surface of the things you can do with Netlify without
reaching out to 3rd part services, and I hope I gave you a reason to try it
out.
Previewing branches
The GitHub integration works great with Pull Requests.
Every time you push a Pull Request, Netlify deploys that branch on a
speci c URL which you can share with your team, or to anyone that you
want.
Clicking the link points you to the special URL that lets you preview the PR
version of the site.