Wednesday, January 13, 2016

Angular2 TypeScript Hello World App Setup with VS 2015 and ASP.NET 5 RC1


  1. InstallVisual Studio 2015
  2. Install ASP.NET 5 RC1 which contains new templates you’ll need for this.
  3. Install npm which you’ll need to get our Angular2 and associated third party dependencies
  4. If you’re in a corporate environment you’ll need to configure your npm proxy settings to get past all this:
    npm config set proxy http://proxy.company.com:80/
    1. If you have a proxy to get through you’ll need to figure out what your proxy is.  If you’re company is using a .pac file then you’ll need to read it to determine the proxy.  Have fun J
    2. This link is helpful: http://jjasonclark.com/how-to-setup-node-behind-web-proxy/
    3. Emulate the VS Developer command prompt by running this:
    4. Then modify the npm config settings as follows:
    5. This should allow npm to access the outside world.
    6. However it may not.  When you type “npm config set proxy http…” it places the entries in a “.npmrc” file located on your “C:\Users\UserID\.npmrc” path.
      1. If you mistype your proxy or https-proxy command it won’t validate it for you.  It’ll simply put it in there, as is, with no config checking whatsoever.  At least that’s what I think from 10 seconds of experience with it…
      2. My .npmrc file looks like this after the three “set” commands above:
    7. However then again this didn’t work for someone I know.  So we found another entry I’d put in at some point in my travels in the “Environment Variables”:
      1. Add HTTP_PROXY of http://proxy.company.com:80 as shown in the above illustration
      2. Check your NODE_PATH is there as well as it may assist with running "gulp" when you get to that point.
    8. Now test that the config setting is correct:
      npm config get proxy
      1. And it will show this:
      2. If it still shows your http://login:password@http://fdsafdsa then you’ve still got an issue.
    9. It could be that if you have the .npmsrc file in the root of the folder where you’re running this thing then maybe that’ll work.  Feel free to play and figure it out.
  5. Note:  The following was taken from a few web articles:
    1. http://dotnetspeak.com/2015/12/angular-2-beta-asp-net-v-next-release-candidate-and-typescript-so-happy-together - The below steps are largely based on this article.  However it is missing some key things that I struggled with.  So I added those items below.
    2. https://angular.io/docs/ts/latest/quickstart.html - Official startup guide from the Angular folk.  However it’s missing the VS.net setup, etc
    3. Note: In both instances you’ll find more details on “why” we do things in the above links than you’ll find below.  This is an instruction manual. I only go into detail in areas I had trouble with.
    4. Enjoy!
  6. Create a new ASP.Net 5 project:
      1. Choose the “Empty” ASP.NET 5 Template.
      2. Uncheck “Host in the cloud” if checked.
    1. Choose OK to continue
  7. I called my new project “Web.Client”.  Here’s a screenshot of our folder structure:
  8. Setup static file support in the package and application code
    1. Package file update: Open “project.json” and add the static files package
      1. "Microsoft.AspNet.StaticFiles":"1.0.0-rc1-final"
    2. Application code update: Open “Startup.cs” and modify the Configure method as follows:
      1. Add app.UseStaticFiles();
      2. Comment out the Hello World script
  9. Add “index.html” under the wwwroot folder:

  10. Edit the “index.html” file and give it something to tell us:
  11. Build Web.Client so that the Startup.cs changes take effect.
  12. Test that our index.html page can be seen in a browser:
    1. Notes:
      1. At this point we have the bare minimum needed to serve our new “index.html” page
    2. Open a command prompt with administrative privileges:
    3. Navigate to your project directory.  In my case I’ll be navigating to my “Web.Client” directory in the console session:
      cd c:\Sample\Web.Client
    4. Run “dnx web” to start our hosting environment:
      1. You could instead use the “IIS Express” debug option from Visual Studio.
        1. My experience with this is it will work but is very slow.  I personally like Microsoft’s “dnx” command prompt option better at this point…  I mean come on, there is only one “.cs” file and we don’t need to edit it again so why invoke the overhead…
        2. Read up on “DNX” if you want to know more: http://docs.asp.net/en/latest/dnx/overview.html
      2. If “dnx” is not recoginized and throwing an error try “dnvm upgrade” which seems to resolve this issue.
    5. Open a browser and navigate to http://localhost:5000/index.html:
      1. >If you see “Hello World!” then you forgot to either make the Startup.cs changes or build your application prior to executing “dnx web”.  Make both changes, press “Ctrl+C”, then type “dnx web” to reload your app for access through the URL.
  13. Now let’s install our Angular2 components:
    1. Add a new item to the project: “NPM Configuration file” called “package.json”
    2. Open “package.json” and paste these dependencies:
      1. This is the default:
      2. This is after we’ve made our changes:
      3. Here’s the text:
        "dependencies": { "angular2":"2.0.0-beta.0", "systemjs":"0.19.9", "es6-promise":"3.0.2", "es6-shim":"0.34.0", "reflect-metadata":"0.1.2", "rxjs":"5.0.0-beta.0", "zone.js":"0.5.10" },
      4. Note: You can view what the latest versioning of each of these dependencies by replacing the first letter with itself. I’m sure theres a shortcut, but I haven’t put much effort into finding it:
      5. Note: You also hover over each of the dependencies to get a little fan fiction on each of the dependencies:
      6. Note: I ran into an issue going from 2.0.0-beta.0 to 2.0.0-beta.1 when trying to view my Angular2 site in IE11. Worked in beta.0, but not in beta.1. More on that when we get to that section. So for now, use the dependencies provided above. I’ll mention it again below when you get there…
      7. Save your changes to “package.json”
    3. If you’re watching you may see that the that the packages are “restoring…” in your solution:
      1. In your Output you’ll see that npm is installing those dependencies auto-magically:
      2. Wait for the “Restoring…” to complete
  14. Now that we have the dependencies setup we need to put some structure onto where we’ll do our development.  Create a folder called “app” under your project, mine is “Web.Client”
  15. Add a “TypeScript” file  under the new “app” folder and call it “app.ts”. 
  16. Here’s what we’ll have so far in “wwwroot”, “Dependencies\npm”, and “app”:
  17. Edit “app.ts” and put this in there:
    import {Component} from 'angular2/core'; @Component({ selector: 'app-shell', template: '<h1> Angular 2 is working if you see this for {{name}}</h1> ' }) export class app { name: string; constructor() { this .name = "Hello Kitty"; } }
  18. Now we’ll see this when we look at “app.ts” (i.e. notice the compile error):
    1. The screenshot above says “export class Main” when it should say “export class app”
  19. Now we’ll fix the compile error by configuring our typescript behavior by:
    1. Add a “TypeScript JSON Configuration file” at the root of your Project:
    2. By default it shows this:
    3. We want to add a couple things to make our app.ts file sing:
      1. Enable decorators functionality:
        “emitDecoratorMetadata”: true
      2. Enable experimental Decorators (we’re in beta which means it’s all experimental at least that’s my best guess. If you don’t do this the Visual Studio script checker will barf on random things)
        “experimentalDecorators”: true
      3. Use systemjs for module loading
        “module”: “system”
      4. Use node style module resolution:
        “moduleResolution”: “node”
      5. Turn on noImpliciteAny for the heck of it
      6. What we’ll have is this:
    4. Save your changes
  20. Now we need to start our app by using bootstrapping functionality from Angular2.
    1. Create a new “TypeScript” file under the “app” folder called “boot.ts”:
    2. Modify “boot.ts” and put this in it:
    3. import{app}from"./app"; import{bootstrap}from'angular2/platform/browser' bootstrap(app);
      1. In this script we’re pointing to our app.ts’s “app” class and starting it up.
    4. Save your changes
  21. Now we get to use our new app.ts and boot.ts in index.html.  So let’s put it all together
    1. Modify “index.html” in the “wwwroot” folder as follows: <!--DOCTYPEhtml--> <html> <head> <metacharset ="utf-8" /> <title> Angular2 Testing </title> <!-- 1. Load thy libraries --> <scriptsrc ="node_modules/angular2/bundles/angular2-polyfills.js"></script> <scriptsrc ="node_modules/systemjs/dist/system.src.js"></script> <scriptsrc ="node_modules/rxjs/bundles/Rx.js"></script> <scriptsrc ="node_modules/angular2/bundles/angular2.dev.js"></script> <!-- 2. Configure thy SystemJS --> <script> System.config({ packages: { app: { format: 'register', defaultExtension: 'js', } } }); System.import( 'app/boot') .then(console.log( 'Application started...' ), console.log( 'Error occurred while starting application!')); </script> </head> <!-- 3. Display thy application --> <body> <app-shell><h2> Loading or more appropriately, your Angular2 app isn't working yet... </h2></app-shell> </body> </html>
    2. Above script taken from the Angular2 start page at https://angular.io/docs/ts/latest/quickstart.html
    3. Now we need to figure out how to get the “app” folder files we’ve created into the “wwwroot” folder.  Well this problem has been solved by a program called “gulp”.  Here’s how we install, configure, and abuse “gulp” to perform the dependency and “app” folder copies to “wwwroot”.
      1. Install “gulp”
        1. You could try and install gulp at the root of your project but I recommend you do it more globally like so
          1. From a command prompt type:
            npm install gulp –g
            1. This installs the gulp app globally.
            2. Add a “Gulp configuration file” to your Web.Client root folder called gulpfile.js:
            3. Edit your “gulpfile.js” file as follows: /* This file in the main entry point for defining Gulp tasks and using Gulp plugins. Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007 */ var gulp = require('gulp'); // Copy our dependencies to the wwwroot folder gulp.task('thirdparty',function() { gulp.src('./node_modules/angular2/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/angular2')); gulp.src('./node_modules/es6-promise/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/es6-promise')); gulp.src('./node_modules/zone.js/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/zone.js')); gulp.src('./node_modules/systemjs/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/systemjs')); gulp.src('./node_modules/reflect-metadata/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/reflect-metadata')); gulp.src('./node_modules/es6-shim/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/es6-shim')); gulp.src('./node_modules/rxjs/**/*.js') .pipe(gulp.dest('./wwwroot/node_modules/rxjs')); }); //Copy our "app" folder changes over to the wwwroot folder's "app" folder gulp.task('copy',function() { gulp.src('./app/**/*.*') .pipe(gulp.dest('./wwwroot/app')); }); //Optional way of automatically copying over the compiled javascript files over to the wwwroot folder gulp.task('watch',function() { gulp.watch('./app/**/*.js', ['copy']); }); //By default the thirdparty task above will run gulp.task('default', ['thirdparty']);
    4. Save all changes to your solution, which includes your “gulpfile.js” file.
    5. Now we’ll test our “gulp” install
      1. Run “gulp thirdparty” from your project folder location to copy the dependencies over to “wwwroot”
        1. Before: After:
        2. Here is what your command prompt will show:
      2. At this point we would want to run “gulp copy” as well. However we first need to get the app.ts and boot.ts files to compile.
    6. Setup compilation of your TypeScript (.ts) files as follows:
      1. In your VS 2015 solution goto Tools\Options:
      2. Navigate to “Text Editor\TypeScript\Project\General” and set these flags:
      3. You might as well enable “Line Numbers” while you’re at it. I luv line numbers, but if you’re a hater ignore this step:
      4. Choose OK to continue
      5. Before:   After:
      6. Note: You may not see the app.js and boot.js at first.  You may have to jiggle the keys in the lock a little before it’ll take.  In order to get boot.ts to create the boot.js file I put my cursor in the file put a space and saved.  This seemed to trigger the on save compile nature of these TypeScript (.ts) files.
      7. If you have the app.js and boot.js files then we’re ready for the next step
    7. Now we can do the “gulp copy” command:
      1. It puts the root\app files in root\wwwroot\app:
    8. At this point everything is covered… well except for IE11 which you’ll see shortly
    9. Test our file in the browser:
      1. Run “dnx web” again from your project folder in a command prompt:
      2. In Chrome:
      3. In IE11:
        1. Say what???!!!
        2. Ok, so first things first, let’s debug this, press F12 in your IE11 browser window to bring up the developer tools window.
        3. Navigate to the “Console” tab:
        4. See nothing, then refresh your IE11 window and see your debug window refresh:
        5. Note:  There are improved ways of getting better errors returned.  Bower traceur or something like that may help, but I’ve not had a chance to look at that yet.
        6. Anyways, IE11 does not work for your Angular2 code.  See the next steps for a fix.
    10. Fix our IE11 implementation by adding “es6-shim” into index.html as follows before the “system.js” script:
                      <scriptsrc="node_modules/es6-shim/es6-shim.js"></script>
      
      1. The “es6-shim” fixes our IE11 issue and makes the Angular2 code compatible with IE11.
    11. Save your “index.html” change
    12. Reload your “index.html” page in your IE11 browser and now it’s working unless you forgot to save like I did at first…:
      1. Still not seeing it?  Then we’ll repeat what I said earlier.  The beta versions are finicky.  Beta.0 will work, Beta.1 will not work.  If you felt like typing the different dependencies into the “package.json” file then you most likely got defaulted to the most recent version which right now happens to be beta.1.  Change it back to Beta.0 and wait for the dependencies to reload after you saved.  Refresh the page in the browser to make it work.
    13. As an aside, you could open a new command prompt and type “gulp watch” which may annoy you every time you make a change to a file in the root project’s “app” folder.  But then it could have been the automatic .js file updates that occur each time you make a change to the .ts file.
      1. Go into Visual Studio and edit your \app\app.ts file located here:
      2. Edit the template text and choose save.  For grins and giggles I changed the following:
      3. View your changes in IE11 or Chrome… We are in a corporate environment so these are our two choices…
    14. Now if you are like my coworker you hate having to run “gulp” manually via a command prompt.  Never fear for he discovered that you can add gulp to run as part of your build process: http://docs.asp.net/en/latest/client-side/using-gulp.html#running-default-tasks

    15. That’s all I got, enjoy!

No comments:

Post a Comment