10 Languages That Compile to JavaScript

Modern applications have different requirements than simple websites. But the browser is a platform with a (mostly) fixed set of technologies available, and JavaScript remains as the core language for web applications; any application that needs to run in the browser has to be implemented in that language.
We all know that JavaScript is not the best language for every task, and when comes to complex applications, it might fall short. To avoid this problem, several new languages and transpilers of existing ones have been created, all of them producing code that can work in the browser without writing any line of JavaScript and without thinking about the limitations of the language.
This article includes a list of ten interesting languages that can be transpiled to JavaScript to be executed in the browser or on a platform like Node.js.
Dart is a classical, object-oriented language where everything is an object and any object is an instance of a class (objects can act as functions too.) It is specially made to build applications for browsers, servers, and mobile devices. It is maintained by Google and is the language that powers the next generation AdWords UI, the most important product of Google regarding revenue, which is in itself a proof of its power at scale.
The language can be translated to JavaScript to be used in a browser, or be directly interpreted by the Dart VM, which allows you to build server applications too. Mobile applications can be made using the Flutter SDK.
Complex applications also require a mature set of libraries and language features specially designed for the task, and Dart includes all of this. An example of a popular library is AngularDart, a version of Angular for Dart.
It allows you to write type-safe code without being too intrusive; you can write types, but you are not required to do so since they can be inferred. This allows for rapid prototyping without having to overthink the details, but once you have something working, you can add types to make it more robust.
Regarding concurrent programming in the VM, instead of shared-memory threads (Dart is single-threaded), Dart uses what they call Isolates, with their own memory heap, where communication is achieved using messages. In the browser, the story is a little different: instead of creating new isolates, you create new Workers.
// Example extracted from dartlang.org

import ‘dart:async’;
import ‘dart:math’ show Random;

main() async {
print(‘Compute π using the Monte Carlo method.’);
await for (var estimate in computePi()) {
print(‘π ≅ $estimate’);

/// Generates a stream of increasingly accurate estimates of π.
Stream computePi({int batch: 1000000}) async* {
var total = 0;
var count = 0;
while (true) {
var points = generateRandom().take(batch);
var inside = points.where((p) => p.isInsideUnitCircle);
total += batch;
count += inside.length;
var ratio = count / total;
// Area of a circle is A = π⋅r², therefore π = A/r².
// So, when given random points with x ∈ <0,1>,
// y ∈ <0,1>, the ratio of those inside a unit circle
// should approach π / 4. Therefore, the value of π
// should be:
yield ratio * 4;

Iterable<Point> generateRandom([int seed]) sync* {
final random = new Random(seed);
while (true) {
yield new Point(random.nextDouble(), random.nextDouble());

class Point {
final double x, y;
const Point(this.x, this.y);
bool get isInsideUnitCircle => x * x + y * y <= 1;

Get started with Dart
TypeScript is a superset of JavaScript; a valid JavaScript program is also valid TypeScript but adding static typing. The compiler can also work as a transpiler from ES2015+ to current implementations, so you always get the latest features.
Unlike many other languages, TypeScript keeps the spirit of JavaScript intact, only adding features to improve the soundness of the code. These are type annotations and other type-related functionality that makes writing JavaScript more pleasant, thanks to the enabling of specialized tools like static analyzers and other tools to aid in the refactoring process. Also, the addition of types improve the interfaces between the different components of your applications.
Type inference is supported, so you don’t have to write all the types from the beginning. You can write quick solutions, and then add all the types to get confident about your code.
TypeScript also has support for advanced types, like intersection types, union types, type aliases, discriminated unions and type guards. You can check out all these in the Advanced Types page in the TypeScript Documentation site.
JSX is also supported by adding the React typings if you use React.
class Person {
private name: string;
private age: number;
private salary: number;

constructor(name: string, age: number, salary: number) {
this.name = name;
this.age = age;
this.salary = salary;

toString(): string {
return `${this.name} (${this.age}) (${this.salary})`;

Get started with TypeScript
Elm is a purely functional programming language that compiles to JS, HTML, and CSS. You can build a complete site with just Elm, making it a great alternative to JavaScript frameworks like React. The applications that you build with it automatically use a virtual DOM library, making it very fast. One big plus is the built-in architecture that makes you forget about data-flow and focus on data declaration and logic instead.
In Elm, all functions are pure, which means that they will always return the same output for a given input. They can’t do anything else unless you specify it. For example, to access a remote API you would create command functions to communicate with the external world, and subscriptions to listen for responses. Another point for purity is that values are immutable; when you need something, you create new values, instead of modifying them.*
The adoption of Elm can be gradual; it is possible to communicate with JavaScript and other libraries using ports. Although Elm hasn’t reached version 1 yet, it is being used for complex and large applications, making it a feasible solution for complex applications.
One of the most attractive features of Elm is the beginner-friendly compiler, which, instead of producing hard-to-read messages, generates code that helps you to fix your code. If you are learning the language, the compiler itself can be of big help.
Continue reading %10 Languages That Compile to JavaScript%

Link: https://www.sitepoint.com/10-languages-compile-javascript/

Building a Multiplayer TicTacToe Game with Meteor

Meteor is a popular, full stack web framework that makes it very easy to prototype your ideas and get from development to production really fast. Its reactive nature and the use of DDP, make it a great candidate for building simple, multiplayer, browser games.
In this tutorial, I’ll show you how to build a multiplayer TicTacToe with Meteor, using its default front-end templating engine, Blaze. I will assume that you have played around with Meteor a bit, and of course, that you feel comfortable coding with JavaScript.

If you have zero experience with Meteor I’d recommend you first follow the TODO app tutorial on the official Meteor site.

You can find the code for the completed app in the accompanying GitHub repo.
Creating the app
If you don’t have Meteor installed you should follow the instructions on their site according to your OS.
Generate the Scaffolding
Now with Meteor installed, open your terminal and run the following command:
meteor create TicTacToe-Tutorial

This will create a folder with the name of your app (in this case TicTacToe-Tutorial). This new folder contains the basic file structure for an app. There’s actually a sample app inside.
Navigate to the folder:
cd TicTacToe-Tutorial

And now run the app:

I know, I know… that’s a terribly hard-to-remember command, and you’ll be using it a lot, so you should start memorizing it!
If everything went fine now the console should be building the app. After it’s done, open your web browser and go to http://localhost:3000 to see the app running. If you have never done so before, I’d recommend you play around with the sample app. Try to figure out how it works.
Let’s take a look at the file structure. Open your app’s folder. The only things there that we care about (for now) are the client folder and the server folder. The files inside the client folder will be downloaded and executed by the client. The files in the server folder will only be executed on the server and the client has no access to them.
These are the contents in your new folder:
client/main.js # a JavaScript entry point loaded on the client (we won’t be needing this)
client/main.html # an HTML file that defines view templates
client/main.css # a CSS file to define your app’s styles
server/main.js # a JavaScript entry point loaded on the server
package.json # a control file for installing NPM packages
.meteor # internal Meteor files
.gitignore # a control file for git

Building the board
A TicTacToe board is a simple three by three table; nothing too fancy, which is great for our first multiplayer game, so we can focus on the functionality.
The board will be downloaded by the client, so we’ll be editing files inside the client folder. let’s begin by deleting the contents on main.html and replacing it with the following:


<table id=”board">
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>

Don’t forget to save your files after making changes! Otherwise, they won’t be acknowledged by Meteor.
Now let’s add some css to our board. Open the main.css file and add the following content:
margin: auto;
font-family: arial;

height: 200px;
width: 200px;
background-color: lightgrey;
overflow: hidden;

text-align: center;

width: 100px;
height: 50px;
font-size: 25px;

text-align: center;
font-size: 150px;
overflow: hidden;
padding: 0px;
margin: 0px;

text-align: center;
height: 200px;
width: 200px;
padding: 0px;
margin: 0px;

We’ve also added a few extra ids and classes that we’ll be using later on in this tutorial.
Finally, delete client/main.js, as we won’t be needing it, and open the app in the browser to see how it looks.
This is fine and all, but is not an optimal solution. Let’s do some refactoring by introducing Blaze Templates.
Creating a Template
Templates are pieces of HTML code with their own functionality that you can reuse anywhere in your app. This is a great way to break up your apps into reusable components.
Before creating our first template, we’ll add two more folders inside the client folder. We’ll call one html and the other one js.
Inside the html folder, create a new board.html file with the following content:
<template name="board">
<table id="board">
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>

Now, on the main.html folder replace the content inside the body tag with the following code:



This will insert our template with the property name="board", inside the body tag.
But this is the same hard coded board that we had before. Only now, it’s inside a template, so let’s take advantage of the template helpers to build our board dynamically.
Using helpers
We’ll declare a helper in the board template that will provide us with an array with the same length as the dimensions we want our board to have.
inside the js folder create a file called board.js with the following content:
import { Meteor } from ‘meteor/meteor’;
import { Template } from ‘meteor/templating’;

sideLength: () => {
let side = new Array(3);

return side;

Now, we’ll use this helper in the board’s template HTML to repeat one single row for each element in the array provided by the helper. To help us with this, we’ll use the Each-in Spacebars block helper.
Replace the content inside the board.html file with the following:
<template name="board">
<table id="board">


<td class="field" id="">




Notice that we’re looping through the array twice, once for the rows and once for the columns, instantiating the corresponding tag (tr or td) as we go. We’re also setting their id properties as the @index of the row + @index of the column. What we get is a two digits number that will help us identify that element, with its position on the board.
Check out the app at http://localhost:3000 to see how it’s looking so far.
Now that we have a good looking board, we’ll need a play button and a tag to show information on the current game.
Let’s begin by creating the ui.html file inside the html folder… you know the drill. Now, add the following content to it:
<template name ="ui">
<div id="ui">

<p id="status">


<button id="play-btn">Play</button>


As you can see we’re using the #if Spacebars block helper and the inGame helper (that we haven’t yet defined) as a condition. There’s the status helper inside the p tag too. We’ll define that later also.
How does it work? #if the inGame helper returns true, the player will see whatever’s in the status helper. Otherwise, we’ll simply show the play button.
Don’t forget, for this component to be displayed we need to add it to our main client template:



Logging in
We won’t be dealing with any login UI. We will install a very useful package called brettle:accounts-anonymous-auto that will automatically log in all users anonymously into our app.
Head over to your console and run the following command:
meteor add brettle:accounts-anonymous-auto

Now, when you open the app for the first time after adding this package, it’ll create a new user, and every time you open the app on the same browser it’ll remember you. If we’re not keeping any data from said user, it might be better to just remove them when they log out. But we’re not going over that in this tutorial.
Building the Game
Finally, we’re going to start building the game itself! Let’s go over the functionality we’ll be implementing, to have a clear view of what’s coming next.
We’ll need functionality for:
Continue reading %Building a Multiplayer TicTacToe Game with Meteor%

Link: https://www.sitepoint.com/building-multiplayer-tictactoe-game-with-meteor/

MEAN Stack: Developing an app with Angular 2+ and the Angular CLI

The MEAN stack comprises of advanced technologies used to develop both the server-side and the client-side of a web application in a JavaScript environment. The components of the MEAN stack include the MongoDB database, Express.js (a web framework), Angular (a front-end framework), and the Node.js runtime environment. Taking control of the MEAN stack and familiarizing different JavaScript technologies during the process will help you in becoming a full-stack JavaScript developer.
JavaScript’s sphere of influence has dramatically grown over the years and with that growth, there is an ongoing desire to keep up with the latest trends in programming. New technologies have emerged and existing technologies have been rewritten from the ground up (I am looking at you, Angular).
This tutorial intends to create the MEAN application from scratch and serve as an update to the original MEAN stack tutorial. If you are familiar with MEAN and want to get started with the coding, you can skip to the overview section.
Introduction to MEAN Stack
Node.js – Node.js is a server-side runtime environment built on top of Chrome’s V8 JavaScript engine. Node.js is based on an event-driven architecture that runs on a single thread and a non-blocking IO. These design choices allow you to build real-time web applications in JavaScript that scale well.
Express.js – Express is a minimalistic yet robust web application framework for Node.js. Express.js uses middleware functions to handle HTTP requests and then either return a response or pass on the parameters to another middleware. Application-level, Router-level, and Error-handling middlewares are available in Express.js.
MongoDB – MongoDB is a document-oriented database program where the documents are stored in a flexible JSON-like format. Being an NOSQL database program, MongoDB relieves you from the tabular jargon of the relational database.
Angular – Angular is an application framework developed by Google for building interactive Single Page Applications. Angular, originally AngularJS, was rewritten from scratch to shift to a Component based architecture from the age old MVC framework. Angular recommends the use of TypeScript which, in my opinion, is a good idea because it enhances the development work-flow.
Now that we are acquainted with the pieces of the MEAN puzzle, let’s see how we can fit them together, shall we?
Here is a high-level overview of our application.

We will be building an Awesome Bucket List Application from the ground up without using any boilerplate template. The front-end will include a form that accepts your bucket list items and a view that updates and renders the whole bucket list in real-time.
Any update to the view will be interpreted as an event and this will initiate an HTTP request. The server will process the request, update/fetch the MongoDB if necessary, and then return a JSON object. The front-end will use this to update our view. By the end of this tutorial, you should have a bucket list application that looks like this.

The entire code for the Bucket List application is available on GitHub.
First things first, you need to have Node.js and MongoDB installed to get started. If you are entirely new to Node, I would recommend reading the Beginner’s Guide to Node to get things rolling. Likewise, setting up MongoDB is easy and you can check out their documentation for installation instructions specific to your platform.
$ node -v
# v8.0.0

Start the mongo daemon service using the command.
sudo service mongod start

To install the latest version of Angular, I would recommend using Angular-CLI. It offers everything you need to build and deploy your angular application. If you are not familiar with the Angular CLI yet, make sure you check out The Ultimate Angular CLI Reference.
npm install -g @angular/cli

Create a new directory for our bucket list project. That’s where all your code will go, both the front end and the back end.
mkdir awesome-bucketlist
cd awesome-bucketlist

Creating the Backend Using Express.js and MongoDB
Express doesn’t impose any structural constraints on your web application. You can place the entire application code in a single file and get it to work, theoretically. However, your code base would be a complete mess. Instead, we are going to do this the MVC (Model, View, and Controller) way (minus the view part).
MVC is an architectural pattern that separates your models (the back-end) and views (the UI) from the controller (everything in between), hence MVC. Since Angular will take care of the front-end for us, we will have three directories, one for models and another one for controllers, and a public directory where we will place the compiled angular code.
In addition to this, we will create an app.js file that will serve as the entry point for running the Express server.

Although using a model and controller architecture to build something trivial like our bucket list application might seem essentially unnecessary, this will be helpful in building apps that are easier to maintain and refactor.
Initializing npm
We’re missing a package.json file for our back end. Type in npm init and, after you’ve answered the questions, you should have a package.json made for you.
We will declare our dependencies inside the package.json file. For this project we will need the following modules.

express: Express module for the web server
mongoose: A popular library for MongoDB
bodyparser: Parses the body of the incoming requests and makes it available under req.body
cors: CORS middleware enables cross-origin access control to our web server.

I’ve also added a start script so that we can start our server using npm start.
“name": "awesome-bucketlist",
"version": "1.0.0",
"description": "A simple bucketlist app using MEAN stack",
"main": "app.js",
"scripts": {
"start": "node app"

//The ~ is used to match the most recent minor version (without any breaking changes)

"dependencies": {
"express": "~4.15.3",
"mongoose": "~4.11.0",
"cors": "~2.8.3",
"body-parser": "~1.17.2"

"author": "",
"license": "ISC"

Now run npm install and that should take care of installing the dependencies.
Filling in app.js
First, we require all of the dependencies that we installed in the previous step.
// We will declare all our dependencies here
const express = require(‘express’);
const path = require(‘path’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
const mongoose = require(‘mongoose’);

//Initialize our app variable
const app = express();

//Declaring Port
const port = 3000;

As you can see, we’ve also initialized the app variable and declared the port number. The app object gets instantiated on the creation of the Express web server. We can now load middleware into our Express server by specifying them with app.use().
//Middleware for CORS

//Middleware for bodyparsing using both json and urlencoding

/*express.static is a built in middleware function to serve static files.
We are telling express server public folder is the place to look for the static files
app.use(express.static(path.join(__dirname, ‘public’)));

The app object can understand routes too.
app.get(‘/’, (req,res) => {
res.send("Invalid page");

Here, the get method invoked on the app corresponds to the GET HTTP method. It takes two parameters, the first being the path or route for which the middleware function should be applied.
The second is the actual middleware itself and it typically takes three arguments: The req argument corresponds to the HTTP Request; the res argument corresponds to the HTTP Response; and next is an optional callback argument that should be invoked if there are other subsequent middlewares that follow this one. We haven’t used next here since the res.send() ends the request-response cycle.
Add this line towards the end to make our app listen to the port that we had declared earlier.
//Listen to port 3000
app.listen(port, () => {
console.log(`Starting the server at port ${port}`);

npm start should get our basic server up and running.
By default, npm doesn’t monitor your files/directories for any changes and you have to manually restart the server every time you’ve updated your code. I recommend using nodemon to monitor your files and automatically restart the server when any changes are detected. If you don’t explicitly state which script to run, nodemon will run the file associated with the main property in your package.json.
npm install -g nodemon

We are nearly done with our app.js file. What’s left to do? We need to

Connect our server to the database.
Create a controller which we can then import to our app.js.

Setting up mongoose
Setting up and connecting a database is straightforward with MongoDB. First, create a config directory and a file named database.js to store our configuration data. Export the database URI using module.exports.
// 27017 is the default port number.
module.exports = {
database: ‘mongodb://localhost:27017/bucketlist’

And establish a connection with the database in app.js using mongoose.connect().
// Connect mongoose to our database
const config = require(‘./config/database’);

"But what about creating the bucket list database?", you may ask. The database will be created automatically when you insert a document into a new collection on that database.
Working on the controller and the model
Now let’s move on to create our bucket list controller. Create a bucketlist.jsfile inside the controller directory. We also need to route all the /bucketlist requests to our bucketlist controller (in app.js).
const bucketlist = require(‘./controllers/bucketlist’);

//Routing all HTTP requests to /bucketlist to bucketlist controller

Here is the final version of our app.js file.
Continue reading %MEAN Stack: Developing an app with Angular 2+ and the Angular CLI%

Link: https://www.sitepoint.com/mean-stack-angular-2-angular-cli/

Nuxt.js: A Universal Vue.js Application Framework

Universal (or Isomorphic) JavaScript is a term that has become very common in the JavaScript community. It is used to describe JavaScript code that can execute both on the client and the server.
Many modern JavaScript frameworks, like Vue.js, are aimed at building Single Page Applications (SPAs). This is done to improve the user experience and make the app seem faster since users can see updates to pages instantaneously. While this has a lot of advantages, it also has a couple of disadvantages, such as long “time to content" when initially loading the app as the browser retrieves the JavaScript bundle, and some search engine web crawlers or social network robots will not see the entire loaded app when they crawl your web pages.
Server-side Rendering of JavaScript is about preloading JavaScript applications on a web server and sending rendered HTML as the response to a browser request for a page.
Building Server-side rendered JavaScript apps can be a bit tedious, as a lot of configuration needs to be done before you even start coding. This is the problem Nuxt.js aims to solve for Vue.js applications.
What is Nuxt.js
Simply put, Nuxt.js is a framework that helps you build Server Rendered Vue.js applications easily. It abstracts most of the complex configuration involved in managing things like asynchronous data, middleware, and routing. It is similar to Angular Universal for Angular, and Next.js for React.
According to the Nuxt.js docs "its main scope is UI rendering while abstracting away the client/server distribution."
Static Generation
Another great feature of Nuxt.js is its ability to generate static websites with the generate command. It is pretty cool and provides features similar to popular static generation tools like Jekyll.
Under the Hood of Nuxt.js
In addition to Vue.js 2.0, Nuxt.js includes the following: Vue-Router, Vue-Meta and Vuex (only included when using the store option). This is great, as it takes away the burden of manually including and configuring different libraries needed for developing a Server Rendered Vue.js application. Nuxt.js does all this out of the box, while still maintaining a total size of 28kb min+gzip (31kb with vuex).
Nuxt.js also uses Webpack with vue-loader and babel-loader to bundle, code-split and minify code.
How it works
This is what happens when a user visits a Nuxt.js app or navigates to one of its pages via :

When the user initially visits the app, if the nuxtServerInit action is defined in the store, Nuxt.js will call it and update the store.
Next, it executes any existing middleware for the page being visited. Nuxt checks the nuxt.config.js file first for global middleware, then checks the matching layout file (for the requested page), and finally checks the page and its children for middleware — middleware are prioritized in that order.
If the route being visited is a dynamic route, and a validate() method exists for it, the route is validated.
Then, Nuxt.js calls the asyncData() and fetch() methods to load data before rendering the page. The asyncData() method is used for fetching data and rendering it on the server-side, while the fetch() method is used to fill the store before rendering the page.
At the final step, the page (containing all the proper data) is rendered.

These actions are portrayed properly in this schema, gotten from the Nuxt docs:

Creating A Serverless Static Site With Nuxt.js
Let’s get our hands dirty with some code and create a simple static generated blog with Nuxt.js. We will assume our posts are fetched from an API and will mock the response with a static JSON file.
To follow along properly, a working knowledge of Vue.js is needed. You can check out Jack Franklin’s great getting started guide for Vue.js 2.0 if you’re a newbie to the framework. I will also be using ES6 Syntax, and you can get a refresher on that here: https://www.sitepoint.com/tag/es6/.
Our final app will look like this:

The entire code for this article can be seen here on GitHub, and you can check out the demo here.
Application Setup and Configuration
The easiest way to get started with Nuxt.js is to use the template created by the Nuxt team. We can install it to our project (ssr-blog) quickly with vue-cli:
vue init nuxt/starter ssr-blog

Note: If you don’t have vue-cli installed, you have to run npm install -g vue-cli first, to install it.

Next, we install the project’s dependencies:
cd ssr-blog
npm install

Now we can launch the app:
npm run dev

If all goes well, you should be able to visit http://localhost:3000 to see the Nuxt.js template starter page. You can even view the page’s source, to see that all content generated on the page was rendered on the server and sent as HTML to the browser.
Next, we can do some simple configuration in the nuxt.config.js file. We will add a few options:
// ./nuxt.config.js

module.exports = {
* Headers of the page
head: {
titleTemplate: ‘%s | Awesome JS SSR Blog’,
// …
link: [
// …
rel: ‘stylesheet’,
href: ‘https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.2/css/bulma.min.css’
// …

In the above config file, we simply specify the title template to be used for the application via the titleTemplate option. Setting the title option in the individual pages or layouts will inject the title value into the %s placeholder in titleTemplate before being rendered.
We also pulled in my current CSS framework of choice, Bulma, to take advantage of some preset styling. This was done via the link option.

Note: Nuxt.js uses vue-meta to update the headers and HTML attributes of our apps. So you can take a look at it for a better understanding of how the headers are being set.

Now we can take the next couple of step by adding our blog’s pages and functionalities.
Working with Page Layouts
First, we will define a custom base layout for all our pages. We can extend the main Nuxt.js layout by updating the layouts/default.vue file:
Continue reading %Nuxt.js: A Universal Vue.js Application Framework%

Link: https://www.sitepoint.com/nuxt-js-universal-vue-js/

Creating Beautiful Charts Using Vue.js Wrappers for Chart.js

Charts are an important part of modern websites and applications. They help to present information that cannot be simply represented in text. Charts also help to make sense of data that would ordinarily not make sense in a textual format by presenting them in a view that’s easy to read and understand.
In this article I will show you how to represent data in the form of various types of chart with the help of Chart.js and Vue.js.
Chart.js is a simple yet flexible JavaScript charting library for developers and designers that allows drawing of different kinds of chart by using the HTML5 canvas element. A good refresher on Chart.js can be read here.
Vue.js is a progressive JavaScript framework, which we’ll use alongside Chart.js to demonstrate the chart examples. There’s an awesome primer on using Vue.js on Sitepoint and that can be read here. We’ll also be using vue-cli to scaffold a Vue.js project for the demo we are going to build. vue-cli is a simple CLI for scaffolding Vue.js projects. It offers various templates from which an app can be built, but we will be using the webpack template to bootstrap our app.
Charts, Charts, Charts
There are different types of JavaScript charting libraries and various chart wrappers built on Vue.js, but as we are focused on Chart.js in this article, we will be looking at Vue wrappers for Chart.js.
There is an awesome collection of Vue wrappers for charts on the awesome-vue repo on GitHub but we are only interested in the following Chart.js wrappers:


We will be using the various wrappers to demonstrate how to create different types of chart and also touch on the unique features that each of these wrappers possesses.
Scaffolding the Project with vue-cli
Let’s get started by installing vue-cli with the following command:
npm install -g vue-cli

Once that’s done, we can then get started with scaffolding a project by typing in:
vue init webpack my-project

We are specifying that we want a Vue.js app created for us with the webpack template and the name of the project as my-project. Respond to all of the questions and let vue-cli do the rest of the magic. Awesome!
Now let us go ahead to install the dependencies and Chart.js wrappers needed for our app:
npm install chart.js chartkick hchs-vue-charts vue-chartjs vue-chartkick

Tip: If you use npm 5, no need for the –save flag anymore as all packages are automatically saved now. Read more about that here.

This will install all the dependencies and Chart.js Vue wrappers needed. Let’s test what we have so far and run our application and see if the app was successfully created. According to the vue-cli docs, running npm run dev will create a first-in-class development experience in which we can interact and engage with our app. So let’s do that.
npm run dev

You can visit localhost:8080 in your browser to see the welcome page.
Adding Routes
Next thing we want to do is create the different routes in which we can view the charts for each of the wrappers above. At the end, we would like to have a /charts route to display charts made with the vue-charts wrapper, /chartjs to display charts made with the vue-chartjs wrapper, and lastly /chartkick to display charts made with the vue-chartkick wrapper.
Navigate to the router folder of the app and open up theindex.js file. Let’s replace the content of that file with this:
import Vue from ‘vue’ // Import Vue from node_modules
import Router from ‘vue-router’ // Import Vue Router from node_modules
import Home from ‘@/components/Home’ //The Home component that’s in charge of everything we see on the app’s homepage
import VueChartJS from ‘@/components/VueChartJS’ //The VueChartJS component that displays the vue-chartjs charts.
import VueChartKick from ‘@/components/VueChartKick’ //The VueChartJS component that displays the vue-chartkick charts.
import VueCharts from ‘@/components/VueCharts’ //The VueChartJS component that displays the vue-charts charts.

//Specify that we want to use Vue Router

export default new Router({
routes: [
path: ‘/’,
name: ‘Home’,
component: Home
path: ‘/chartjs’,
name: ‘VueChartJS’,
component: VueChartJS
path: ‘/chartkick’,
name: ‘VueChartKick’,
component: VueChartKick
path: ‘/charts’,
name: ‘VueCharts’,
component: VueCharts

Before we discuss the code above, make sure to create the files below in the src/components/ folder. This is done so that the routes defined above have their own component.


So what’s happening in the code block above?
We imported some files which are the Vue components that we created above. Components are one of the most powerful features of Vue. They help us extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue’s compiler attaches behavior to.
Lastly, we defined the routes and components which will serve the different pages we need to display the different charts.
Home Component
As mentioned above, the Home component serves as the default (/) route and we will need to create it. We can do that, or simply rename the existing Hello.vue file to Home.vue and replace the content with the code block below.