Rails, AngularJS (1.5.8), and Webpack — Part 3

Alrighty then. Where were we? I believe we left off in a good place. We installed the webpacker gem, and seemed to have communication between our newly created JS file and our app. Now for the hard part. I’m still learning this stuff myself, so bear with me. We’re going to attempt to use ES6 modules instead of the old way of declaring AngularJS components and such. This style guide is a good starting point to get to know what your components will look like and how they’ll interact with each other.

Setting up the Main Module

The first thing we’ll want to do is setup up our main Angular module in app/javascript/packs/application.js. First we have to import angular into the file so our module knows what it’s attaching itself to. We are also going to export the module, which will allow our webpack to compile it when we run app in the terminal.

// app/javascript/packs/application.js

import angular from 'angular';

const meals = angular.module('meals', [])

export default meals;

Now we have to declare our app in our main html file: app/views/layouts/application.html.erb. So in the body tag, add ng-app=”meals”.

<!DOCTYPE html>
<html>
  <head>
    <title>Meals</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all' %>
    <%= javascript_include_tag 'application' %>
    <%= javascript_pack_tag 'application' %>
  </head>

  <body ng-app="meals">
    <%= yield %>
  </body>
</html>

Now our app knows that it’s an Angular app and it’s looking for a module called ‘meals’. Let’s add a route with a component so we can actually see something working on the Angular side of the world.

Routing With angular-ui-router

If you’ve built anything with Angular in the past, you’ve most definitely used angular-ui-router. We’re going to install it with yarn. If you don’t have yarn installed, check out the installation instructions here. To install, or ‘add’ as it’s called in yarnish, head over to your terminal and type: ‘yarn add angular-ui-router’. If you check your dependencies in your package.json file, you should see ‘angular-ui-router’ listed.

So let’s see if we can get a route working. In our angular_home.html file, let’s add a ui-view directive.

<-- app/views/application/angular_home.html -->

<ui-view></ui-view>

This will give us an entry point into AngularLand and let us declare routes with $stateProvider in a config function. Back in our application.js file, let’s add a config function and a route. First we’ll have to import the ui-router so we can use all of its goodness. Check it…

// app/javascript/packs/application.js

import angular from 'angular';
import uirouter from 'angular-ui-router';

const meals = angular.module('meals', [uirouter])
  .config(($stateProvider) => {
    $stateProvider
      .state('home', {
        url: '/',
        template: `<h1>Hola Mundo!</h1>`
      })
  })

export default meals;

Ok so here we’re importing the angular-ui-router and chaining a config function onto our module. Angular-ui-router gives us access to $stateProvider, $urlRouterProvider, $state, and $stateParams. In the config function above, we’re using the Arrow function syntax now available in ES6, and setting the state. With a url and a simple template, we should be getting somewhere. Let’s quickly make a link back in angular_home.html so we can see our route is working.

<-- app/views/application/angular_home.html -->

<a ui-sref="home">Home</a>
<ui-view></ui-view>

Run the Webpack and Rails Server Simultaneously?

Now to run webpack, we can’t just run the rails server. We actually have to run the rails and the webpack servers. Back in the terminal, create a new tab in the same directory, then run ‘./bin/webpack-dev-server’. This will compile your included javascript files through webpack. If you’re like me, then you probably got a lot of red errors followed by this line: webpack: Failed to compile.

So something is not letting us load our module. If we scroll up in the terminal, we’ll see that most of the errors say that angular doesn’t exist. But I thought we installed Angular already!! Well, I’m pretty sure that when we installed it with the webpacker command, it installed Angular 4. We need version 1.5.8, which we can easily install add with yarn. Exit out of the webpack server in your terminal. Then type ‘yarn add angular@1.5.8’.

Check out your package.json file and you should see angular with the correct version listed under the dependencies. Now if we try to run the server again – ‘./bin/webpack-dev-server’ – everything should compile (there might be a few warnings, but let’s not worry about those). In your other tab run the rails server command and in your browser go to ‘localhost:3000’. You should see a link that says ‘Home’. Click it, and you should be routed to the home route that we set up earlier. If you followed along, you should see ‘Hola Mundo!’ on the webpage!

To Sum it Up

We are in the Angular business now! In this episode, we’ve connected the front end to our meals app with webpack, added angular-ui-router and AngularJS, created our main module with a route and template, learned how to run the webpack server, and saw our template working in the browser. Next time, we’ll get some functionality going with some http requests to the backend and do something a little more exciting than Hello World Hola Mundo. As always, thanks for reading. I hope this helps someone out there! Until next time…CHEERS:)

Advertisements

How to Clone a Website Using Chrome’s Dev Tools Part I

Ever want to copy a website? Well, it’s pretty easy – especially with Chrome’s Dev Tools! I find it pretty useful to go into someone else’s code to see how they’re doing what they’re doing. Then you can implement new cool features for sites you’re working on. I’m not going into complicated websites with API’s and the like; just a simple static site.

I’m going to be using Carbon Five’s website as reference. First head on over there, then right click on the page and select ‘view page source’. This will show us all the html for the page. Now just select all (command + ‘a’) and copy. In your text editor of choice (I’m using Atom), create an index.html file and paste the html there. You’ll see a bunch of files that are referenced in the ‘head’ of the document. We’ll have to copy the non-CDN local files into our text editor.

We’re going to open each file from the page source and copy file into our text editor.

Screen Shot 2017-07-02 at 3.41.31 PM

Create folders for each type of file, ie. javascripts, stylesheets, images, etc. We’re going to do what we did above when copying and pasting all of the HTML. Starting from the ‘javascripts/showup.js’ file in the head of the view source page document, click on each file, select all, copy (noticing a trend?) and paste into a newly created file in Atom. Name the file the same as the file you’re copying from. From here, let’s see where we stand by opening the index.html file in Chrome. Go ahead, I’ll wait…

Screen Shot 2017-07-02 at 5.24.47 PM

It should look something like this

Woah! All of a sudden we’re in 1995 and Nirvana’s on the radio! We’re getting the bare bones HTML here. Let’s take a look in the console to see what’s going on under the hood. Command + option + ‘j’ will get us there. Notice all of the errors.

Screen Shot 2017-07-02 at 5.30.38 PM

That’s a lotta red

There are a ton of files that can’t be found. There are definitely some files we haven’t looked at yet, but let’s focus on the ones we have. Our file directory must be different than Carbon Five’s. All we have to do is reference them a bit differently than we are.

Let’s look at the non-CDN files in the ‘head’ of our index.html page. They all start with a forward slash, but if we’re referencing from the index.html file, we’ll have to prepend them with a single period to jump up to the root directory. Start from the ‘showup.js’ file start adding.

<script type="text/javascript" src="/javascripts/showup.js"></script> // This
// Turns into 
<script type="text/javascript" src="./javascripts/showup.js"></script>

When you’re done (remember to save), refresh your index.html file in Chrome. You’ll notice a few things happened. The page has some styling now – not great, but it’s something. Next, we have less errors in the console. Sweet! Let’s keep going and turn these errors green.

In the console, notice how the cdn files which can’t be found start with two forward slashes. Since they are referencing outside websites as opposed to local files, we’ll have to prepend them with ‘https:’, and they should be good to go. Back in our index.html file, let’s do just that. Once you’re done, notice how the links turn blue. We now have good links. Go back to your browser and refresh.

Screen Shot 2017-07-02 at 5.41.40 PM

Getting there!

Now we’re talking! Since we’re now referencing the bootstrap cdn files correctly, we have our navbar looking good and the page layout is looking much better. Next time, we’ll add images and conquer any other errors we come across. Until then, CHEERS:)