Tag Archiv: learn
Learn Webpack in 15 Minutes
Build tools have become an integral part of web development, mainly due to the ever-increasing complexity of JavaScript apps. Bundlers allow us to package, compile, and organize the many assets and libraries needed for a modern web project.
In this tutorial we will take a look at webpack, a powerful open-source bundler and preprocessor that can handle a huge variety of different tasks. We’ll show you how to write modules, bundle code, and use some of the loader plugins. The tutorial is designed for total beginners to webpack, but having some JavaScript knowledge is advised.
Why webpack?
Much like any other aspect of web development, there isn’t a standard for which build tool to use. Right now, developers have to choose between webpack, Gulp, Browserify, NPM scripts, Grunt, and like 10 others. There are many in-depth comparisons out there, but all of these tools are very similar, so most of the time it comes down to personal preference and what project you are working on.
Here are some pros and cons to help you decide whether webpack is the tool for you:
Pros:
- Great for working with singe-page apps
- Accepts both
require()
andimport
module syntaxes - Allows for very advanced code splitting
- Hot Reload for quicker development with React, Vue.js and similar frameworks
- Мost popular build tool according to the 2016 JavaScript survey
Cons:
- Not suitable for beginners in web development
- Working with CSS files, images, and other non-JS resources is confusing at first
- Documentation could be better
- Changes a lot, even most 2016 tutorials are already outdated
1. Installation
The easiest way to install webpack is by using a package manager. We will go with npm but feel free to use Yarn or another hip alternative. In both cases you need to have Node.js on your machine and a package.json ready to go.
It is preferred to install it locally (without the -g
tag). This will make sure everyone working on your project has the same version of webpack.
npm install webpack --save-dev
Once we have it installed, it’s best to run webpack via a Node.js script. Add these lines to your package.json:
//... "scripts": { "build": "webpack -p", "watch": "webpack --watch" }, //...
Now by calling npm run build
from the terminal we can make webpack bundle our files (the -p
option stands for production and minifies the bundled code). Running npm run watch
will start a process that automatically bundles our files when any of them change.
The last part of the setup is to tell webpack which files to bundle up. The recommended way to do this is by creating a config file.
2. Webpack Config File
Here we will look at the config file in its most basic form but don’t let that fool you – the webpack config file is quite powerful, varies a lot from project to project, and can become super complex in some cases.
In the root directory of your project add a file called webpack.config.js.
webpack.config.js
var path = require('path'); module.exports = { entry: './assets/js/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } };
The entry option tells webpack which is our main JavaScript file. There are many different strategies for configuring entry points but in most cases a single entry is enough.
In output we specify the name and path of our bundle. After running webpack we will have all our JavaScript in a file called bundle.js. This is the only script file that we will link in our HTML:
<script src="./dist/bundle.js"></script>
This setup should be enough to get us started. Later we will add some more stuff to it, but first let’s see how modules work.
3. Webpack Modules
Webpack provides multiple ways to work with modules, and most of the time you are free to go with whichever one you like. For this tutorial we will use the ES6 import
syntax.
We want to add a module that greets our users. We create a file called greeter.js and make it export a simple function:
greeter.js
function greet() { console.log('Have a great day!'); }; export default greet;
To use this module, we have to import it and call it in our entry point, which if you look back at the config file is index.js.
index.js
import greet from './greeter.js'; console.log("I'm the entry point"); greet();
Now when we run the bundler with npm run build
, and open our HTML in the browser, we see this:
Our entry point and our greeter module were compiled into one file called bundle.js and it was executed by the browser. Here is a simple flow chart of what’s happening so far:
4. Requiring Libraries
We want our app to specify which day of the week it is when it greets users. To do so we will use moment.js by directly importing it into our greeter module.
First we need to install the library via npm:
npm install moment --save
Then in our greeting module, we simply import the library exactly the same way we imported local modules in the previous point:
greeter.js
import moment from 'moment'; function greet() { var day = moment().format('dddd'); console.log('Have a great ' + day + '!'); }; export default greet;
After we bundle up again to apply the changes, in the browser console we will have the following messages:
Our flow diagram now looks like this:
Note: There are other, more advanced techniques for including libraries but they are outside the scope of this article. You can read more about them here.
5. Loaders
Loaders are webpack’s way to execute tasks during bundling and pre- or post-process the files in some manner. For example, they can compile TypeScript, load Vue.js components, render templates, and much more. Most loaders are written by the community, for a list of popular loaders go here.
Let’s say we want to add a linter to our project that checks our JS code for errors. We can do so by including the JSHint loader, which will catch all kinds of bad practices and code smells.
First we need to install both JSHint and the webpack JSHint loader:
npm install jshint jshint-loader --save
Afterwords, we are going to add a few lines to our webpack config file. This will initialize the loader, tell it what type of files to check, and which files to ignore.
webpack.config.js
var path = require('path'); module.exports = { entry: './assets/js/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, // Add the JSHint loader module: { rules: [{ test: /\.js$/, // Run the loader on all .js files exclude: /node_modules/, // ignore all files in the node_modules folder use: 'jshint-loader' }] } };
Now when webpack is started, it will show us a list of warnings in the terminal (which we will ignore):
Since moment.js is located in the node_modules folder, it won’t be linted by the JSHint loader:
Further Reading
This concludes our introduction to webpack! Since this is a lesson for beginners, we tried to cover only the most useful and must-know concepts of webpack. We hope the tutorial has been helpful, not too confusing, and within the 15 minute limit from the title.
In the near future, we are planning to add a second part to this tutorial, explaining how to work with CSS modules and other more-advanced features. In the meantime, if you want to learn more about webpack (and there is a lot more) we recommend checking out these awesome resources:
- webpack.js.org – The official website for the project, lots of guides and docs available there.
- Awesome webpack – Curated list of webpack resources.
- Webpack 2 – A full tutorial – Almost two-hours-long free video tutorial.
- Webpack Examples – List of various webpack configurations.
15 Interesting JavaScript and CSS Libraries for April 2017
Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.
Core UI
Based on Bootstrap 4, Core UI is an admin template offering a highly customizable solution to building control panels. There are separate boilerplate versions that allow you to quickly integrate it with some of the most popular frameworks right now: AngularJS, Angular 2, React.js, and Vue.js.
React Trend
A React component by the Unsplash team that can be used to create beautiful line graphs suitable for displaying trending and activity metrics. This project follows a minimalistic approach and gives you a simple, polished solution to one specific problem, so don’t expect a full charting library. An unofficial Vue port is also available here.
Element
Element is a UI framework based on Vue.js 2.0. It includes a set of over 50 components that are styled very consistently, following certain design and color choices. Each element is well documented and super easy to customize and implement into any Vue.js project. There is also a useful Sketch Template of the components for building mockups.
Extension Boilerplate
This project provides us with a solid foundation for creating cross-browser extensions. The boilerplate is based on WebExtensions, making it possible to write extensions once, and then deploy them simultaneously to Chrome, Opera & Firefox. It also has other cool features such as live-reload and a bundle of various Sketch assets needed for submitting to the respective app stores.
BigPicture
Modern lightbox plugin that works simultaneously for images and videos, providing smoothly animated overlay pop-ups. An awesome feature of BigPicute is that it works both with <img>
tags and with background-image
elements, giving developers freedom in their markup. As for the video, YouTube, Vimeo, and direct video links are supported.
Reactive Listener
Don’t let the name fool you, this isn’t a React component. Reactive listener is a tiny library by Zurb that allows us to create advanced event listeners that respond to more complex actions than simply clicks and hovers. Right now it can only recognize when the user is moving towards an element, but in the future more cool listeners may be added.
Eagle.js
Eagle.js is a Vue.js framework for making web-based slideshows, similar to Reveal.js. It supports animations, themes, interactive widgets (for web demos), and makes it easy to reuse components, slides and styles across presentations.
Planck.js
This project is a JavaScript rerwite of the popualr C++ Box2D physics engine, used by game developers for years. Plank.js optimizes the engine for web and mobile browsers, and provides an open-source JavaScript-friendly codebase and API. This way web developers can be more comfortable when making 2D games and other physics related experiments.
Create React Native App
Following the success of the Create React App boilerplate, here is a tool for making React Native apps without the need for any build configuration. It allows for React Native apps to be set up and tested without having to install Xcode or Android Studio.
Pushy Buttons
A tiny library with CSS-only 3D buttons that have a smooth pushing down effect when pressed. The buttons come in 4 sizes and 3 colors and can be easily customized via SASS or by simply modifying the source .css file.
React Overdrive allows developers to animate elements on the page and to create smooth transiitons between the different states (or pages) in an app. The API is component based so setting up transitions is super easy, even when switching between multiple JavaScript files.
MoveTo
Our monthly resources compilation wouldn’t be complete without the addition of at least one click-to-scroll animation library. This month we have moveTo – a zero dependency JavaScript library that is only 1kb gzipped, super easy to use, and utilizes the native window.scroll
API for doing animations.
Anchorme
Anchorme is a powerful JavaScript library that takes any string or text file and detects all the URLs inside it. It is fast, reliable, and has lots of useful features and customization options. Possible use cases include converting links in a text to clickable HTML <a>
tags, extracting URLs from a string, or as a validator for emails, URLs, and IPs.
RPG Awesome
Free icon font that is packed with nearly 500 fantasy themed vector icons. It covers everything from weapons and armor to magic and inventory items. RPG Awesome can be used just like any other web icon font (<i class="ra ra-sword"></i>
) and is customizable via simple CSS or SASS.
Tent CSS
Tent CSS is a framework (or as its creators call it a CSS survival kit) that provides you with all the basic necessities needed for building a responsive website. It is very lightweight (only 5kb gzipped), follows the BEM standard, and has a modern flexbox grid for doing layouts.
15 Interesting JavaScript and CSS Libraries for April 2017
This April we have prepared for you a wonderful list of web dev resources, including some React libraries, a framework for cross-browser extensions, and a JavaScript physics engine!Finally! CSS Triangles Without Ugly Hacks
Anyone who has tried to make HTML upvote arrows, speech bubbles or other pointy elements, knows that in order to create a CSS-only triangle you have to use some sort of hack. The two most popular solutions are to create your triangles out of borders, or to use unicode characters.
We have to admit that both these CSS hacks are pretty clever but they still are terrible solutions, and as such make our code much uglier and less flexible. For instance, we can’t have a triangle with a background image, since borders and characters can only be one color.
Introducing Clip-path
Clip-path is a fairly new addition to the CSS spec that allows us to show only part of an element and hide the rest. Here is how it works:
Let’s say we have an ordinary rectangular div
element. You can click Run in the editor below to view the rendered HTML.
(Play with our code editor on Tutorialzine.com)
To make a triangle we will need the polygon()
function. It expects as argument comma separated 2D points which will define the shape of our mask. A triangle = 3 points. Try and change the values to see how the shape transforms.
(Play with our code editor on Tutorialzine.com)
Everything inside the path we created stays, everything outside it is hidden. This way we can make not only triangles, but all sorts of asymmetrical shapes that will behave like regular CSS blocks.
The only drawback of this technique is that we have to carefully calculate the coordinates of our points in order to get a good looking triangle.
Still, it’s way better than using borders or ▲.
Browser Support
If you open the caniuse page for clip-path things don’t look very good at first sight, but in reality the property works perfectly fine unprefixed in Chrome and with the -webkit-
prefix in Safari. Firefox users have to wait till version 53. IE/Edge is behind the curve as usual but we can expect support sometime in the future.
Further Reading
The clip-path
property has many other tricks up its sleeve, including some SVG magic. To find out more about it check out the links below.
- Clip-path on MDN – here
- In-depth tutorial for clip-path on Codrops – here
- Clippy, a clip-path generator – here
Finally! CSS Triangles Without Ugly Hacks
In this quick tutorial we show you how to use the clip-path property to effortlessly create CSS-only triangles. No borders or unicode involved.CSS Grid VS Flexbox: A Practical Comparison
Not too long ago, the layout for all HTML pages was done via tables, floats, and other CSS properties that were not well suited for styling complex web pages.
Then came flexbox – a layout mode that was specifically designed for creating robust responsive pages. Flexbox made it easy to properly align elements and their content, and is now the preferred CSS system of most web developers.
Now we have a new contender for the best-system-to-build-html-layouts trophy (trophy title is a work in progress). It is the mighty CSS Grid, and by the end of this month, it will be available natively in Firefox 52 and Chrome 57, with other browsers (hopefully) following soon.
A Basic Layout Test
To get a sense of what it’s like to build layouts with each system, we’ve build the same HTML page twice – once with flexbox, and another time with the CSS grid. You can download both projects from the Download button near the top of the article, or inspect them in this online demo:
The design is pretty basic – it consists of a centered container, inside of which we have a header, main section, sidebar, and a footer. Here are the main “challenges” that we’ll have to solve, while keeping CSS and HTML as clean as possible:
- Position the four major sections of the layout.
- Make the page responsive (the sidebar goes below the main content on smaller screens).
- Align the contents of the header – navigation to the left, button to the right.
As you can see, for the sake of the comparison we’ve kept everything very simple. Let’s start with problem number one.
Challenge 1: Position The Page Sections
Flexbox Solution
We’ll start off with the flexbox solution. We add display: flex
to the container and direction its children vertically. This will position all the sections one under another.
.container { display: flex; flex-direction: column; }
Now we need to make the main section and the sidebar stand next to each other. Since flex containers are generally one-directional, we will need to add a wrapper element.
<header></header> <div class="main-and-sidebar-wrapper"> <section class="main"></section> <aside class="sidebar"></aside> </div> <footer></footer>
We then make the wrapper display:flex
and flex-direction
it in the opposite direction.
.main-and-sidebar-wrapper { display: flex; flex-direction: row; }
The last step is to set the size of the main section and the sidebar. We want the main content to be three times the size of the sidebar, which isn’t hard to do with flex
or percentages.
.main { flex: 3; margin-right: 60px; } .sidebar { flex: 1; }
As you can see flexbox did pretty well, but we still needed quite a lot of CSS properties + an additional HTML element. Let’s see how the CSS grid will do.
CSS Grid Solution
There are a couple of different ways to use the CSS grid, but we will go with the grid-template-areas syntax, as it seems most suitable for what we are trying to accomplish.
First we will define four grid-area
-s, one for each page section:
<header></header> <!-- Notice there isn't a wrapper this time --> <section class="main"></section> <aside class="sidebar"></aside> <footer></footer>
header { grid-area: header; } .main { grid-area: main; } .sidebar { grid-area: sidebar; } footer { grid-area: footer; }
Then we can set up our grid and assign the placement of each area. The code below may seem quite complicated at first, but once you get to know the grid system it becomes really easy to grasp.
.container { display: grid; /* Define the size and number of columns in our grid. The fr unit works similar to flex: fr columns will share the free space in the row in proportion to their value. We will have 2 columns - the first will be 3x the size of the second. */ grid-template-columns: 3fr 1fr; /* Assign the grid areas we did earlier to specific places on the grid. First row is all header. Second row is shared between main and sidebar. Last row is all footer. */ grid-template-areas: "header header" "main sidebar" "footer footer"; /* The gutters between each grid cell will be 60 pixels. */ grid-gap: 60px; }
And that’s it! Our layout will now follow the above structure, and because of the way we’ve set it up we don’t even have to deal with any margins or paddings.
Challenge 2: Make Page Responsive
Flexbox Solution
The execution of this step is strongly connected to the previous one. For the flexbox solution we will have to change the flex-direction
of the wrapper, and adjust some margins.
@media (max-width: 600px) { .main-and-sidebar-wrapper { flex-direction: column; } .main { margin-right: 0; margin-bottom: 60px; } }
Our page is really simple so there isn’t much to rework in the media query, but in a more complex layout there will be lots and lots of stuff to redefine.
CSS Grid Solution
Since we already have the grid-areas
defined, we just need to reorder them in a media-query. We can use the same column setup.
@media (max-width: 600px) { .container { /* Realign the grid areas for a mobile layout. */ grid-template-areas: "header header" "main main" "sidebar sidebar" "footer footer"; } }
Or, we can redefine the entire layout from scratch if we think that’s a cleaner solution.
@media (max-width: 600px) { .container { /* Redefine the grid into a single column layout. */ grid-template-columns: 1fr; grid-template-areas: "header" "main" "sidebar" "footer"; } }
Challenge 3: Align Header Components
Flexbox Solution
Our header includes some links for navigation and a button. We want the nav to be on the left and the button on the right. The links inside the nav have to be aligned properly next to each other.
<header> <nav> <li><a href="#"><h1>Logo</h1></a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </nav> <button>Button</button> </header>
We’ve already done a similar layout with flexbox in one of our older articles – The Easiest Way To Make Responsive Headers. The technique is really simple:
header { display: flex; justify-content: space-between; }
Now the navigation list and the button are properly aligned. All that is left is to make the items inside the <nav>
go horizontally. It’s easiest to use display: inline-block
here, but since we are going full flexbox, let’s apply a flexbox-only solution:
header nav { display: flex; align-items: baseline; }
Only two lines! Not bad at all. Let’s see how CSS grid handles it.
CSS Grid Solution
To split the nav and the button we will have to make the header display: grid
and set up a 2-column grid. We will also need two extra lines of CSS to position them at the respective borders.
header{ display: grid; grid-template-columns: 1fr 1fr; } header nav { justify-self: start; } header button { justify-self: end; }
As for the inline links inside the navigation – we couldn’t get it quite right with CSS grid. Here is how our best try looks:
The links are inline but they can’t be properly aligned, since there isn’t a baseline
option like in flexbox’s align-items
. We also had to define yet another subgrid.
header nav { display: grid; grid-template-columns: auto 1fr 1fr; align-items: end; }
It’s clear that the CSS grid struggled with this part of the layout, but that isn’t too surprising – it’s focus is on aligning containers, not so much the content inside them. It just isn’t meant for doing finishing touches.
Conclusion
If you’ve made it through the whole article (in which case great job!), the conclusion shouldn’t come as a surprise to you. The truth is, there isn’t a better system – both flexbox and the CSS grid are good at different things and should be used together, not as alternatives to one another.
For those of you who skip directly to the conclusion of articles (no worries, we do it too), here is a summary of the comparison:
- CSS grids are great for building the bigger picture. They makes it really easy to manage the layout of the page, and can even handle more unorthodox and asymmetrical designs.
- Flexbox is great at aligning the content inside elements. Use flex to position the smaller details of a design.
- Use CSS grids for 2D layouts (rows AND columns).
- Flexbox works better in one dimension only (rows OR columns).
- There is no reason to use only CSS grids or only flexbox. Learn both and use them together.
CSS Grid VS Flexbox: A Practical Comparison
We take a look at the new CSS Grid system and compare it with flexbox to see which is the better layout building tool.15 Interesting JavaScript and CSS Libraries for March 2017
Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a handpicked collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention.
Propeller
Propeller is a CSS components framework based on Bootstrap and Google’s Material Design language. It includes 25 components made with responsiveness in mind and featuring the typical Material Design animations. The project can be downloaded as a theme for Bootstrap, a full framework, or as stand alone components.
BaguetteBox
BaguetteBox is a pure JavaScript library for creating responsive lightbox galleries. It is very lightweight, mobile-ready, easy to use and customize, and utilizes CSS3 transitions for buttery-smooth image transitions.
We recently used this library in the making of our freebie pack of 4 Bootstrap Gallery Templates, and we can say we enjoyed working with BaguetteBox a lot.
Whitestorm
Framework for developing 3D web apps and games using the Three.js engine. It provides straightforward wrappers for many common Three.js tasks, making it easier to set up an environment, create objects, add physics, and more. There is an official boilerplate project to get you started, as well as a tool for integration with React.
Animatelo
Animatelo is a port of the extremely popular Animate.css library that replaces the CSS transitions with Web Animations API clones. All of the original Animate.css effects are recreated, but the API is now based on JavaScript methods instead of CSS classes. The library is lightweight and jQuery independent, but may require a polyfill on older browsers.
FuseBox
FuseBox is a bundle loader for JavaScript and CSS with optional add-ons for TypeScript, Sass, and more. It is created with simplicity and performance in mind, providing a viable alternative to webpack. To get you started there are quick boilerplate projects for Angular 2 + TypeScript, React + Babel, Vue.js, Electron, and others.
Yargs
Yargs is a framework for building full-featured command line applications with Node.js. It allows you to easily configure commands, parse multiple –arguments, and setup shortcuts. It even generates help menus automatically.
WebGradients
A large collection of beautiful color gradients that can be easily applied to any HTML page. The project’s website allows you to quickly glance over the available gradients, see them in full screen, and one-click copy them as a CSS property.
Sticky-Kit
Sticky-kit is a jQuery plugin that allows you to attach elements to a certain area on the page, making them stick to it’s boundaries. This way you can have a sidebar that is always visible and scrolls with the rest of the page, but can be contained within its parent container.
ScrollDir
Super-lightweight, no-dependencies JavaScript library for monitoring scroll direction and movements. ScrollDir watches the movement of the scrollbar and toggles an up/down data-attribute on an element of your choice. It ignores small scroll movements, creating a smooth, non-jittery experience.
Svgo
Node.js tool for optimizing SVG files, stripping them from various unnecessary information such as editor metadata, comments, hidden elements, and other attributes that don’t affect the rendered vector. SVGO has a plugin-based architecture, so you can freely choose what to remove and what to leave in.
Store.js
Store.js is a cross-browser solution for advanced local storage. Recently, a version 2 was released, refreshing many of the features and adding extra functionality, such as array/object operations and improved expiration options.
In the previous issue of our monthly web dev resources list, we featured a similar library called localForage. It provides many of the same features as Store.js, but has a more localStorage-like syntax. Make sure to check it out as well.
Snarkdown
Snarkdown is a super simple Markdown parser written in JavaScript. Admittedly, it’s not the most complicated or full-featured parser, but it’s probably the easiest to implement. Snarkdown is only 1kb in size and has only a single method, making it perfect for quick projects where a full parser would be overkill.
Unfetch
The Fetch API is a modern rework of the XMLHttpRequest interface, giving developers a much better way to handle asynchronous requests. Although it’s support now covers most modern browsers, the fetch()
method is still unavailable in IE.
This brings us to Unfetch – a reliable polyfill in under 500 bytes.
Scrollanim
Vanilla JavaScript library for on-scroll animations. Scrollanim offers lots of customization options, separate HTML and JavaScript APIs, and over 50 smooth animation effects thanks to the built-in Animate.css dependency.
Neurojs
JavaScript framework for experimenting with deep learning in the browser, featuring a full-stack neural network that can be trained via reinforcement-learning. The project showcases a cool Demo app where self-driving cars learn to navigate in a 2D environment.