Dart web development with Visual Studio Code

A quick start guide...

Published on 17 January 2017

Visual Studio Code is rapidly becoming my go-to editor for anything not project-oriented C#/F#. I've switched from Atom to VSC for editing my (statically-generated, Markdown driven) blog and have used it for authoring powershell scripts, dockerfiles and much, much more. So, when I decided I wanted to write some Dart code, it was the obvious choice.

Why Dart?

Why did I decide on Dart? Well, I had project I wanted to undertake that featured some... shock horror... dynamic web content. If that isn't enough to send chills down your spine, you've either never had to look at getting started with modern web development or you've already drunk the cool-aid.

Either way, most rational people in the industry will (in the moments of clarity between writing off the last framework as dated and evangelising the next) reluctantly admit that modern web development is a mess. But this is the world we live in and the best one can do is dodge the analysis paralysis and mitigate the majority of the risks. For me, this was adopting a strongly-typed modern development language that has a strong web pedegry and just get on with it.

But in Visual Studio Code?

Why not? It's a great editor and already has great support for Dart courtesy of Danny Tuppeny's excellent Dart extension. Furthermore, I try to keep my development machine as lean and clean as possible so I didn't want to have to install an IDE specifically for Dart development.

Fortunately, as you'll see, getting set up for Dart development with Visual Studio Code is very easy, doesn't require any installation (everything is "xcopy" deployed) and you can start being productive almost right away.

Ingredients

You will need the following:

  • Visual Studio Code - obviously
  • DartVS - the Dart language extension for Visual Studio Code
  • The Dart SDK - the code Dart binaries and tools needed for dart development
  • Dartium - a version of Chrome (even called "Chrome.exe") with a built in Dart runtime

Steps

  1. Download and extract the Dart SDK to a location on your HD (I use C:\Apps for "manually" installed tools/applications so will be using the path C:\Apps\dart-sdk).
  2. Download and extract Dartium to a location on your HD (C:\Apps\chromium for me).
  3. Create a new directory wherever you keep your source files and name it GettingStartedWithDart.
  4. In this directory, create two further directories named lib and web (this structure follows the Pub Package Layout Conventions).
  5. Start Visual Studio Code and open the GettingStartedWithDart folder. You should see something like this:
Empty Project
  1. If you haven't already, install the DartVS extension by hitting Ctrl-Shift-X (the keyboard shortcut for "View->Extensions") and type Dart in the search box. This should show the "Dart Code" extension by "Danny Tuppeny". Click install and reload the window when complete.
  2. As we haven't elected to add the Dart SDK to the path, we need to tell the Dart extension where it can find the SDK. This is done by editing the User Settings (File->Preferences->User Settings) and adding the following settings:
    "dart.sdkPath": "C:\\Apps\\dart-sdk",
    "dart.debugSdkLibraries": false,
    "dart.debugExternalLibraries": false
  1. Back in the Explorer view (Ctrl-Shift-E) add a new file to the web directory named main.dart. We'll populate this file shortly but, for now, it's just so that VSC (and DartVS) realises that this is a Dart project.
  2. Add another new file named pubspec.yaml to the root directory. This file tells the Dart compiler (named Pub) how to build your Dart project and follows a very simply format. In this file add name, dependencies and transformers as shown below:
name: GettingStartedWithDart
dependencies:
transformers:
  1. When you save this file, you should see the Output panel appear showing the output of the Pub command. This is a feature of the DartVS extension which runs a pub get command whenever you save the pubspec.yaml file. As you can probably guess from the output (shown below) the purpose of this command is to retrieve/update any dependencies you've declared in the dependencies section. Also, once the pub get command has run, you should see a new pubspec.lock file appear in the root directory.
Get Dependencies
  1. As we're focusing on using Dart for web development, we'll also add an HTML document we'll manipulate using Dart. To do this, simply add new file named index.html to the web directory and populate it with the following:
<html>
  <head>
    <title>Getting Started With Dart</title>
    <script type="application/dart" src="main.dart"></script>
  </head>
  <body>
    <h1 id="header">Hmm... what should I say?</h1>
  </body>
</html>
  1. At this point you should have the following layout in your project and we're ready start start writing some Dart.
    [Source Directory]
    |-> [Project Name] (i.e. "GettingStartedWithDart")
    | | -> lib
    | | -> web
    | | | -> index.html
    | | | -> main.dart
    | | -> pubspec.lock
    | | -> pubspec.yaml
  1. In the main.dart file, add the following code. (Note, if you type this code rather than copy-pasting it, you'll notice the excellent intellisense features provided by VSC and implemented beautifully by Dart VS.)
import 'dart:html';

void main() {
  querySelector('#header').text = 'Ah yes... Hello World!!!';
}
  1. Right, now we have an HTML file and some Dart code and we're ready to run. While you could run this code manually from the command line, if you're intending on doing more than just this getting started guide, I'd very much recommend setting up some task runners in VSC. This is done by opening the command palette (Ctrl-Shift-P) and typing Configure Task Runner, which should show you the command Tasks: Configure Task Runner. Select this and you will see a list of build systems VSC can automatically create a task runner for (shown below). As Dart isn't one of the predefined templates, select "Others" to create an empty Tasks file.
Configure Task Runner
  1. This command should create a new file called tasks.json in a new .vscode directory and will contain the following json.
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "echo",
    "isShellCommand": true,
    "args": ["Hello World"],
    "showOutput": "always"
}
  1. If you're not familiar with configuring VSC task runners, I'd very much recommend clicking the link in this file to see what the task runner is able to do and how to configure it. However, for your convenience, I have provided my configuration below:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "C:\\Apps\\dart-sdk\\bin\\pub.bat",
    "isShellCommand": true,
    "args": [],
    "showOutput": "always",
    "echoCommand": true,
    "tasks": [
        {
            "taskName": "build",
            "args": [],
            "isWatching": false
         },
        {
            "taskName": "serve",
            "args": [],
            "isWatching": true
         }
    ]
}
  1. As you will probably be able to determine, this file contains two tasks; one named build and the other named serve. The build command compiles your code and checks for errors while the serve command sets up a local web-server (by default bound to port 8080) capable of serving the content of the web directory. Lets try both.

  2. Open the command palette (Ctrl-Shift-P), delete the '>' prompt and then type task followed by a space. You should see the two tasks defined above appear. Continue to build and then hit return. At this point, the output pane should appear displaying the Tasks output and your code should be compiled (and, transpiled into JS!). This is shown below:

Tasks and Build output
  1. If everything is successful, you should see the message 'Built 2 files to "build"'. Now we can test our Dart code by serving it through pub server. To do this, start the task serve task in a similar manner to the task build above. As this task is an isWatching command, the task won't complete when run but will emit messages to the output pane when changes occur. This is shown below:

  2. With a local web-server serving out HTML file and Dart code, we can finally start to use Dartium to run the code. Note that, we're using Dartium because we'll be executing the Dart code directly (rather than the transpiled JavaScript) and Dartium has a built-in Dart runtime which allows for advanced debugging of our Dart code. Start Dartium but executing it from either command line or GUI (exists at C:\Apps\chromium\chrome.exe for me) and, once started, navigate to http://localhost:8080 and you should see the following:

Success!!

Congratulations, you've just run your first Dart code.

If something went wrong and you don't see the header text change from 'Hmm... what should I say?' to 'Ah yes... Hello World!!!' then you can use Dartium's Developer Tools (Ctrl-Shift-I) to view errors and add breakpoints so you can work out what has gone wrong. The developer tools are shown here:

Dartium Developer Tools

You can find loads more information online about the Dart Language and Dart Web Development. Versions of Dart are changing rapidly (there was a minor update while writing this post!) and a thriving support community.

As a (mainly) C# developer I found Dart super easy to get up to speed with and the Visual Studio Code/Dartium combo to be extremely productive. Hopefully you will too.

Have fun.