Writing Our First Component

As we specified in tsconfig.json location for our first component will be src/app.ts. Within the file we import from the ngBackbone core module class View and decorator @Component. By using @Component we declare that underlying view has to bind to ng-hello element of the DOM and use Hello World! string as template:

import { Component, View } from "ng-backbone";

@Component({
  el: "ng-hello",
  template: `Hello World!`
})

class HelloView extends View {
}

let hello = new HelloView();
hello.render();

To compile TypeScript in JavaScript we run:

npm run build

In HTML we just need to set binding element ng-hello that we refer in the component:

<html>
  <head>
    <title>Hello world!</title>
    <meta charset="utf-8">

  </head>
  <body>
    <ng-hello>Loading ...</ng-hello>
  </body>
</html>

Something is missing, isn't it? Of course we need to load Backbone and its dependencies:

Well, we have Backbone, but have to oad the app itself. According to the tsconfig.json TypeScript compiler has generated CommonJS-compliant module. Thus to run it we have at least two options:

  • We can use SystemJs/Webpack to load it asynchronously

  • We can bundle it for in-browser use with Browserify

Bundling App with Browserify

Browserify bundles the source CommonJS module with all the dependent modules encountered recursively into a single file, suitable for in-browser use. If you have not installed Browserify you can do it that easy:

With Browserify we bundle our app source like that:

When we have build/app.bundled.js we load our app straight in the HTML:

Loading App with SystemJS

On the contrary to Browserify, SystemJs loads the module and all the encountered dependencies on-the-fly. If we choose this way, here is what we need to add to HTML:

In any case we result with 'Hello World!' string rendered in the browser:

Last updated

Was this helpful?