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:
<!-- Backbone -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
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:
sudo npm i browserify -g
With Browserify we bundle our app source like that:
browserify build/src/app.js -o build/app.bundled.js
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:
<!-- Module loader -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.37/system.js"></script>
<script>
System.config({
paths: {
"*": "node_modules/*"
},
packageConfigPaths: [ "./node_modules/*/package.json" ],
packages: {
".": {
format: "cjs",
defaultExtension: "js"
}
}
});
System.import( "./build/app" );
</script>
In any case we result with 'Hello World!' string rendered in the browser:
Last updated
Was this helpful?