Aurelia

Unexpected token import with gulp

I have started to play with the release version of Aurelia. My current goal is to see what it takes to get going with Aurelia and ASP.NET Core now that both are RTM. I have hit a couple of road blocks that have ended up being new post of their own. For example this post that covers converting a new ASP.NET Core application to use gulp is one example. Today’s post is going to cover another issue I hit trying to use the gulp tasks created by the Aurelia CLI. There will not be anything Aurelia related in this post that will another post at a later date.

gulp setup

My gulpfile.js is nothing but a reference a directory of tasks. The full file looks like the following.

require('require-dir')('tasks');

Then I have a single task in tasks/exampleTask.js that consists of the following.

import gulp from 'gulp';

gulp.task('helloGulp', function(done){
 console.log('Hello Gulp!');
 done();
});

The error

With the above in place if you look at the task runner explorer you will see that Gulpfile.js shows a failed to load error instead of the helloGulp task.

gulpfailedtoload

As suggested by task runner explorer open the output window. There are many different things that use the output window so be sure and change show output from option to Task Runner Explorer. With that done you will be able to see why the task failed to load. The following is the error I am getting.

Failed to run "C:\ProjectDirectory\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
C:\ProjectDirectory\tasks\exampleTask.js:3
import gulp from 'gulp';
^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at requireDir (C:\ProjectDirectory\node_modules\require-dir\index.js:116:33)
    at Object.<anonymous> (C:\ProjectDirectory\gulpfile.js:1:85)

The fix

I did some googling and I found this post by Mark Goodyear on using ES6 (or ES 2015) with gulp. It turns out the tasks generated by the Aurelia CLI are using ES 2015 and in order to use ES 2015 with gulp there are a few steps that must be taken first. Mark does a great job explaining those steps, but I am going to include a summary from the Visual Studio perspective.

Verify the devDependencies section in package.json contains the following. require-dir is only required if your gulpfile or tasks are using it.

"devDependencies": {
  "gulp": "3.9.1",
  "babel-preset-es2015": "^6.9.0",
  "require-dir":  "^0.3.0" 
}

Next create a .babelrc file at the same level as the package.json file with the following contents.

{
  "presets": [ "es2015"]
}

Then rename gulpfile.js to gulpfile.babel.js.

Back in the Task Runner Explorer hit the refresh button in the top left of the window which should now load your list of tasks under Gulpfile.babel.js with no errors.

taskrunnerrefersh

 

Unexpected token import with gulp Read More »

Aurelia Validation the Replacement Library

The post from last week on Aurelia Validation is now useless as this blog post from the Aurelia team states validation has been completely overhauled. This post is going to feel very similar to last weeks, but using the new validation library. The details on adding a main.js will match exactly from last weeks post, but is being included to make sure the examples in this post are complete.

Installation

Validation in Aurelia is provided using a plugin in which must be installed before being used. Make sure you have npm and jspm installed. For more information on getting up and running with Aurelia check out this post that will guide you through the process and links to a Github repo with matching code.

From the console execute this command jspm install aurelia-validatejs to download and install the files needed for validation.

In order to load plugins a named Aurelia-App is need to allow more control of the bootstrapping process. In Views/Home/Aurelia.cshtml make the following change.

Before:
<div aurelia-app>

After:
<div aurelia-app="main">

Now that this Aurelia application has been named “main” Aurelia will look for a matching main.js file and call its configure function during the bootstrapping process. Here is the main.js I am using. Note that the validation plugin in is being loaded. For my project main.js is located in wwwroot/Aurelia.

export function configure(aurelia) {
    aurelia.use
      .standardConfiguration()
      .developmentLogging()
      .pluginin('aurelia-validatejs');

    aurelia.start().then(() => aurelia.setRoot());
}

Usage

The first step in using validation is to add its import to the top of the class that will be using it.

import {ValidationEngine, Validator, required, email} from 'aurelia-validatejs';

Next setup the validation rules using decorators and inject validation via the constructor and set up the validation rules. The plugin also supports a fluent style of adding validation to property, but I ran into issues getting it working so I just stuck with decorators for this post.

static inject() { return [Validator]; }

@required 
Name = '';

@required 
@email 
Email = '';

constructor(validator) {
    this.reporter = ValidationEngine.getValidationReporter(this);
}

The above makes sure that Name is required and that email is required and conforms to the rule of what an email address. This is only a small sample of the built in validations provided by check out this page for a sample of the other provided validations.

Show Validation Failures in a View

The validation plugin in provides a way to display validation messages with the appropriate field. The following is a part of a view that contains name and email address that are bound to the properties from above.

<form>
    <div class="form-group">
        <label>Name</label>
        <input type="text" value.bind="Name & validate" class="form-control">
    </div>
    <div class="form-group">
        <label>Email</label>
        <input type="email" value.bind="Email & validate" class="form-control">
    </div>
</form>

By adding & validate as part of the value bind statement the plug in knows where the validation messages show be shown.

Warning

If you run into a “Cannot read property ‘bindingContext’ of null” when trying to implement the new validation plugin make sure your class constructor contains:

this.reporter = ValidationEngine.getValidationReporter(this);

From what I can tell this requirement will be temporary. This is an alpha release of the overhaul and has a few rough edges such as the binding context gotcha and the fluent API issues I mentioned above. With the track record of the Aurelia team I am sure the issues I hit will be resolved quickly.

Aurelia Validation the Replacement Library Read More »

Aurelia Validation

Update: this post is now out of date an updated version can be found here.

Client side validation is an important part of client side frameworks and can provide users with immediate feedback as well as check away to stop before posting data to the server. This post is going to look at validation with in Aurelia.

Installation

Validation in Aurelia is provided using a plugin in which must be installed before being used. Make sure you have npm and jspm installed. For more information on getting up and running with Aurelia check out this post that will guide you through the process and links to a Github repo with matching code.

From the console execute this command jspm install aurelia-validation to download and install the files needed for validation.

In order to load plugins a named Aurelia-App is need to allow more control of the bootstrapping process. In Views/Home/Aurelia.cshtml make the following change.

Before:
<div aurelia-app>

After:
<div aurelia-app="main">

Now that this Aurelia application has been named “main” Aurelia will look for a matching main.js file and call its configure function during the bootstrapping process. Here is the main.js I am using. Note that the validation plugin in is being loaded. For my project main.js is located in wwwroot/Aurelia.

export function configure(aurelia) {
    aurelia.use
      .standardConfiguration()
      .developmentLogging()
      .pluginin('aurelia-validation');

    aurelia.start().then(a => a.setRoot());
}

Usage

The first step in using validation is to add its import to the top of the class that will be using it.

import {Validation} from 'aurelia-validation';

Next the inject validation via the constructor and set up the validation rules.

static inject() { return [Validation]; }
constructor(validation) {
    this.Name = '';
    this.Email = '';
    this.validation = validation.on(this)
        .ensure('Name').isNotEmpty().hasLengthBetween(3, 50)
        .ensure('Email').isNotEmpty().isEmail();
}

The above makes sure that Name is required and has a length between 3 and 50 characters and that email is required and conforms to the rule of what an email address contain. This is only a small sample of the built in validations provided by check out this page for a demo of the other provided validations.

Show Validation Failures in a View

The validation plugin in provides a custom attribute that will loop all nested child elements and display validation messages with the appropriate field. The following is a part of a view that contains name and email address that are bound to the properties from above.

<form role="form" validate.bind="validation">
    <div class="form-group">
        <label>Name</label>
        <input type="text" value.bind="Name"placeholder="name" class="form-control">
    </div>
    <div class="form-group">
        <label>Email</label>
        <input type="email" value.bind="Email" placeholder="email" class="form-control">
    </div>
</form>

You can see that the validate custom attribute is bound to the validation property of the class defined above. Since the controls are in a form group the validation plugin is able to infer where bound field is show validation errors in the appropriate area. Check out this page for more details on visualization of validation errors. The default visualization is based on Twitter Bootstrap, but that can be changed the details of which can be found here.

Issues

Unfortunately I ran into some problems with trying to implement validation in a more complex situation dealing with an object that is replaced via binding. I doubt this is a problem with Aurelia. If anyone has any experience with validation on objects that are fully replaced via binding please let me know. Expect a blog post once I get my issue figured out.

Aurelia Validation Read More »