Using Sass, ES6, and Modules
Alright, video five. We're really starting to get into the swing of things here.
In the last four videos we learned how to set up our project, create a database and database tables using migrations. Finally, we learned how to use middleware to set up a RESTful API.
This is going to be a fairly short video because luckily there's not much prep work we need to do, we can just start writing code from the get-go. If you recall, our current home page looks like this.
Let's go ahead and modify that header to use a new font and color. All of my front-end code lives in the public directory. My sass files are in public/styles, and my Sass entry point is main.scss. Let's go into main.scss and modify our h1 element to have a color #333 and a font-family of Open Sans with a fallback to sans-serif. Great, I'm also going to give it a hover state color of #999. Here I'm using sass nesting and the & notation for referencing a parent selector. This is not native CSS functionality, but it will be pre-processed using Sass.
If we check back in our browser and refresh the page you can see that our heading changes and has a new hover state as well. It's that simple. All features of Sass will work right out of the box.
Using this code is now simple. Inside of my main.js I can create a new variable called showMessage and import my showMessage code using the require statement by passing in the path to that file. Whatever got exported from that file is the value that showMessage inside of my main.js file will assume.
We can change our alert here to call the showMessage function that we imported. Let's check it out in the browser.
Let's refresh the page first. Works like a charm.
The way that modules work on the front-end is by using a tool like webpack or browserify. Perk supports both webpack and browserify, and you can configure which tool you'd like to use my modifying the build.js file inside of the script directory. I find that webpack is better for development because it's super fast, but browserify is better in production because it produces smaller compiled files.
The last thing I want to mention about modules is that if you prefer the ES6 module syntax using import and export that is also supported on the front-end, however it is not supported on the backend. All of your node code must use CommonJS.
Summary & Notes
What did we do this time?
What is coming up next time?
Next time we're going to continue with the front-end by setting up our single page app structure with React and React Router.
What resources should they check out? / Reminder about questions
In the resources below I've included the code we wrote today as well as links to the Sass documentation and some solid tutorials for CommonJS and ES6 Modules.