# Getting started with package management using NPM’s package.json file in VSCODE

The files used in this blog can be found here: https://github.com/PhilWolf91/blog_package_json

### Precursor

I’ve really been getting into VSCode recently when doing my own projects and even at work. One thing I’ve noticed is that packages seem to be handled a little differently between using something like a feature-packed IDE like Visual Studio 2015 compared to Visual Studio Code or another editor like Sublime or Brackets. In Visual Studio 2015 you generally have proj files like a .csproj and/or a .sln which would handle packages using a list of entries in a package.config file which is used by NuGet. The entries would probably look a little something like

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="angularjs" version="1.5.8" targetFramework="net452" />
<package id="bootstrap" version="3.3.7" targetFramework="net452" />
<package id="jQuery" version="1.9.1" targetFramework="net452" />
</packages>

This package.config file would install angularjs, bootstrap, and jquery to a nice and tidy Scripts folder and you wouldn’t really have to worry about them again unless you wanted to update the packages. Other Developers coming onto the project would most likely already have those files in source or would be able to run a NuGet restore to get those files into their environment. Package.json works kind of in the same way except it uses packages from NPM, stores those packages in a node_modules directory, and generally come with insanely long file paths that drive Windows and myself mad (the package will have dependencies, which will have dependencies, which will have dependencies… etc, outcome = long ass file paths).

### Getting Started

Alright… so lets start off with an empty website and lets add some basic files to start off

All of these files are empty except the .gitignore which has one entry… node_modules/
This is because node_modules shouldn’t be placed into source and only on the machines that will be developing the app or the server running the app (so part of the build/deployment process would be to run ‘npm install’ so that all the dependencies are available on deployment)

Ok. So what the hell do we do now? We’ve got an empty package.json file… what goes in it? Well, with a little help from VSCode’s intellisense… it’s pretty easy to know what can go in this file along with some help from NPM’s documentation located here https://docs.npmjs.com/files/package.json.

As its a JSON file, you might be able to infer that you’d start off with some squiggly brackets and that properties will be listed in normal JSON format using “property”: “value”… so what happens when we attempt to add a new property?

Well hi there intellisense, long time no see, are those the properties I can use in the file? Why yes, yes they are. I can see two properties already that’ll be helpful, 1) author and 2) dependencies. So if we begin to enter author, we’ll see what this property is suppose to contain in terms of it’s value.

OK Cool, so the author property is supposed to include information about me. Now, in your own project you don’t really need to add this property as its really more helpful for when you actually put a lib on NPM so people can know who created the package as that’s what you’re essentially doing by using package.json, you’re entire project is now technically a ‘package’. Filling out the author though intellisense will allow you to tab-complete a new object for its value so once that’s done you can then start to add properties of the object belonging to ‘author’

As you can see, the object that belongs to ‘author’ contains email,name, and url properties. Lets fill those out really quick. After adding those properties to the object ‘author’ will be happy it has been given the correct data. But you may notice there is a green squiggly under the very first bracket… why is this?

Looks like the package.json file is looking for two properties right off the bat that we don’t have, lets go ahead and add those. After seeing how the author property was added, you should be able to have intellisense help you add these two properties. You should end up with something that looks like this:

Ok. So that’s nice, we’ve got this information in our package.json but… WHAT ABOUT THE DEPENDENCIES?!?!? That’s what you’re here for in the first place, right?

So if you read Getting Started section you’ve been exposed to the intellisense provided by VS Code in the package.json file and you might be able to conclude that intellisense will also help us with adding dependencies… you’d be correct. Remember seeing dependencies in the intellisense from before? Lets try adding that property now.

By clicking on the blue ? icon next to ‘dependencies’ when intellisense pops up, you’ll see the full version of the description for this property. Ok, so this property contains the dependencies of our package AKA our project. Let’s tab complete it and see what we get.

Alrighttttt, so this is where intellisense abandons us, and for good reason… there’s a shit ton of packages out there and trying to fit them all in that intellisense window would be kind of asinine and probably be a humongous load to handle. So, in order to begin adding the dependencies we want, we have to go checkout npmjs.com for the packages we need. So say we want Angular…

That first package looks right to me, lets add it to the dependencies. Add “angular”: “” under dependencies and that will tell package.json to install any version of angular available, which means it will choose highest version it can find and install it.

What if we want a specific version, or, near a specific version if that version cannot be found? Well, intellisense can actually help us out here but it requires the first number and decimal to pick up. We can see the current version on npmjs, the screenshot above shows that angular is currently on 1.5.8 so lets start to define the version as 1.5.8… but wait… what is that intellisense?

VSCode can pick up on the rest of version… but sometimes there are different options that’ll show up here. Sometimes you’ll get the prefixes on the version to appear to which show how can infer which version to use based on a specific version. Here’s the documentation from npmjs.com to show you your available options for versions:

So we now know that we can do a lot of different things when specifying the version such as expecting an exact version, multiple ways to choose a version close to the one we specify using > and < variants as well as using git repositories to get packages instead of NPM’s repository. Lets try finishing the angular dependency by using an exact version then adding another dependency to jQuery but use a variant of the version selector.

Intellisense on jQuery is giving me the option to use the approximate version, so lets give that a shot. Ok. Cool. How do we actually install these dependencies now?

If you’ve followed through this far, you might realize I’ve made a mistake. The version needs to be in a specific format for node, something like v1.0.0 instead of 1.0 so lets go ahead and change that now.

After you’ve filled out your package.json with the dependencies (and fixed the version number!) all you have to do is run ‘npm install’ through the command prompt or a terminal. I prefer using VScode’s built in terminal which can be opened by pressing CTRL +  (backtick) at the same time.

If you look in the TERMINAL window in bottom-middle of the screen you can see ‘npm install’ was ran, a few errors about missing details in the package.json file which aren’t required and the packages were installed. Looking at the Explorer pane on the right you can see that there is now a node_modules directory with angular and jquery installed.

Congratulations – You’ve officially created your first package.json file and installed dependencies onto your machine!

# AngularJS: $routeParams in a SPA In Angular, there’s a service called$routeParams which takes a combination of the $location services search() and path() methods and allows the URI of the current$location to be picked apart and used as variables. The $routeParams service is dependent on the ngRoute module. My explanation isn’t that grand, but check it out in action below! To start off using the$routeParams, you’ll first need to inject ‘ngRoute’ into the app’s main module.

var app = angular.module(‘app’, [‘ngRoute’]);

Next, the routes need to be configure to use the route parameters. This us done using the  ‘:’ syntax in the $routeProvider’s first parameter, the route. This will define the route parameter. $routeProvider.when('/dire', { templateUrl: 'partials/directory.html' });

$routeProvider.when('/dire/:user', { templateUrl: 'partials/userDetails.html' }); The first route will take users to a list of users ( I originally wanted it to be ‘/directory’… but for some reason the routes didn’t show… so I changed it to ‘/dire’ for short… don’t judge me). The second route makes use of the ‘:’ syntax which allows the route to vary and also be pulled out using$routeParams[“user”] in the controller which can be used to define a variable or passed into an $http request. Next, a simple controller for each page that is being routed to. Each controller gets$location injected into it, but $routeParams only gets injected into the userDetailsController. ( Don’t mind the$http being injected into the directoryController… I forgot to remove that ).

The directoryController contains a simple array of users and a function for changing the $location which passes in the selected user as the parameter for the route. The userDetailsController takes defines$scope.user to equal the ‘user’ $routeParam (remember the ‘/dire/:user’ route? this is how we make use of the :user part). To bring everything together, a couple simple views are in order. The page that will display the ‘directory’ ( or ‘dire’ in this case >.> ) will just display buttons with each users name. Ng-Click will allow the use of the chooseName function, it passes in the user’s first name. <div ng-controller="directoryController" style="padding-right:10px;"> <label>Choose a person from the list below</label> <button class="btn btn-info btn-block" ng-repeat="user in users" ng-click="chooseName(user.firstName)">{{user.firstName}}</button> </div>  The second view uses an expression to display the route’s parameter. <div ng-controller="userDetailsController"> <label>The Route Parameter</label> {{user}} </div> ` Here’s what the final results look like: Now, this was a very crude example of using$routeParams BUT it should (if I was clear in explaining how it works…) help to start seeing different ways you can use it to you own benefit as it’s a very useful tool.

# AngularJS: Creating a factory and returning data in a SPA.

Providers (I’ve seen many people just refer to Providers as Services, Angular docs use Providers, so that’s what I’m using >.< ) in Angular provide a way to fetch and persist data inside your web application. There are a couple different variations of providers which from what I can tell, and the large number of equally confused individual on the web, they’re all pretty much the same. There are providers, factories, values, and services, the one that you use is pretty much up to you depending on your need. The reply by Jonathon Palumbo on StackOverflow does a pretty good representation of what all of them look like as well clarifications like that fact that factories and services actually use providers ‘under the hood’. Again, a little confusing. Whatever.

I’m going to go over creating a factory which will fetch some data for me and then return it so that I can use that data in a controller to display on my web page.

So say I want to retrieve a list of users and display them to my page. This is where the factory comes in, it will retrieve the data for us. Then, the controller will bind the data. Finally, a web page will display the data.

#### Creating a Factory

Creation of a basic factory is easy. First, create a module to contain the factory.

The module is named app and the ngRoute module is passed in (if you want more information on ngRoute, checkout my last blog post). Now that we have a module, we can create the factory with .factory(‘factoryName’, function(){});

The first parameter is the name of the factory, the second is a function which will return data. The name of this factory is userRepository and what I want to do with it is return a list of users. To do so, a function needs to be added to the return in order to retrieve the list of users.

The return statement now contains a function called getAllUsers which returns an array of static users. The factory is now complete and this data can be bound in a controller to a view. This can be done by creating a controller and passing in or injecting the userRepository factory which will then make use of the getAllusers function.

#### Passing the Factory to a Controller

The first param is the controllers name, userController and the second is function which takes in the $scope service and the userRepository factory so that we can use it. Then, inside the function,$scope.users gets defined as the return data from UserRepository.getAllUsers(); – and that’s all we need for the controller.

Now, the reason I put ‘in a SPA’ is just because of how i’m going to associate the controller to my web page, which happens to just be a partial page in a Single Page Application (SPA). Associating a controller to a page in a SPA is super easy because in the \$routeProvider.when method, you can use the controller: param to pass in the controller name

#### Adding the controller to the (partial)web page

In red is the .when for the page that I’ll be using the controller with and in green is the actual use of the controller: parameter.

#### Displaying the factory’s data

The only thing left to do is to display the data in users.html, a simple  ng-repeat will display all entries in the array provided by the factory in getAllUsers().

#### The result

When the web app loads up and the users page is visited, it’ll look like this:

# A bit of AngularJS: Directives, Expressions, Modules, and Controllers

Angular is a JavaScript Framework (pretty popular too) for developing web-based applications. The Angular framework is useful in creating vibrant dynamic documents instead of just static pages.

### Installing/Preparing Angular

In order to begin using Angular in your HTML, you must reference angular.js or angular.min.js. In order to reference the script, you must have the script in your site’s directory. If using an IDE such as Visual Studio, you can just download the AngularJS Nuget Package which will include a butt ton of Angular related scripts. If you don’t have the ability to download via NuGet, you can just download one of the angular scripts from Angular’s web page or wherever it may be acquired from and place it in your working dir. Once the script is available, reference it with the <script src=”path\to\angular.min.js”> element.

### Directives & Expressions

Angular makes use of keywords called Directives that act as markers to tell the HTML that some JavaScript is about to be ran or referenced. The first directive that will be used on any web application is called ng-app. The reason that it’ll be the first is that this tells the page when to start making use of the Angular framework. The ng-app directive can be placed virtually anywhere in the HTML as long as it’s before the attempt to do anything else with Angular. Here’s an example of using ng-app, when the expression ( Identified by the double curly braces, expressions are how values are displayed onto the page) is before the directive it’s not evaluated. When the expression is after the ng-app directive then it’s evaluated correctly.

If I wanted to, I could have just put the ng-app directive into the beginning <body> or even the <html> elements.

### Modules

Modules are where the application components live. They’re basically containers for different parts of the app such as controllers and filters.

In the HTML page, you have the ability to declare the module you want to use in the ng-app directive; However, without a module defined in a .js file, nothing will be accomplished as it won’t actually reference anything. Here’s what defining a module in a .js file would look like.

The name of the module is the first parameter provided, the second parameter, the array, is for more advanced module configurations. Now that the module has been created, the ng-app directive in the HTML page can have the module set as it’s value.

Now, if the page is loaded, the expression won’t be evaluated. This is because the .js file must be referenced in the HTML before the module is able to be found correctly. It uses the same script element as the reference to the angular.min.js file. Here’s a screenie of the script reference, the ng-app directive with the module included and the expression.

You’re probably going… “What the hell is the use of the module then?”. The module doesn’t really do anything at the moment. It’s just an empty container. In order to begin making use of the module, we need to add some content to it, such as a Controller.

### Controllers

Controllers are a way to handle data with values and methods which will define the apps behavior. A controller can be defined in a .js file along with a module. Here’s a controller added to the previously created module.

There’s a few alterations made to the JS file. First, it’s considered a good practice to encompass the entirety of a controller within a function. Line 1 and 14 display the containment function. Line 3 is the module created from before.  Lines 5-8 create a _person object which will contain my first and last name, this object will be used in the controller. Lines 10-12 actually create the controller by using the app variable that was defined as the module, this is because the controller is a method of modules in Angular. The first parameter of the controller is it’s name, the second is a function which defines what the controller actually does. All this controller currently does is instantiates another person object equal to _person, doing so allows the object to be used in the HTML.

Now that the controller has been established, it can be used by the HTML via expressions. But first, a new directive must be used, ng-controller. ng-controller tells the HTML what the name of the controller is to be used on the page.

Line 11 shows the use of the ng-controller directive, the value provided let’s the directive know that a controller named indexController is what needs to be referenced and will be utilized in the HTML as simply controller. Line 12 and 13 show expressions utilizing the indexController… as… controller (see how that works? :P). The expressions reference the person object in the controller and each property that the object holds and displays them on-screen. Here’s the final results.

I intend to continue a line of Angular posts for the stuff that I’ve been learning and they should all build upon the previous post. Stick around if you’re interested and drop any comments if you’ve got any questions.