Loading...

Follow SitePoint - JavaScript on Feedspot

Continue with Google
Continue with Facebook
or

Valid

Nowadays, we’re forced to use many accessory tools to facilitate, speed up and optimize our web development workflow. Often though, such tools add an extra layer of complexity into the stack. As a result, we need to utilize additional time and effort to learn, understand and use these tools correctly. The same is true for webpack.

When using webpack for the first time, it can be difficult to understand how it works and how it should be used. Although it has good documentation, it can be daunting for novices, and it has a steep learning curve. However, webpack is worth learning and can save considerable time and effort in the long run. In this tutorial, I’ll introduce all the core concepts to help you get started.

Note: in this tutorial I’ve used webpack 4.30.

What Is Webpack?

As its core, webpack is a static module bundler. In a particular project, webpack treats all files and assets as modules. Under the hood, it relies on a dependency graph. A dependency graph describes how modules relate to each other using the references (require and import statements) between files. In this way, webpack statically traverses all modules to build the graph, and uses it to generate a single bundle (or several bundles) — a JavaScript file containing the code from all modules combined in the correct order. “Statically” means that, when webpack builds its dependency graph, it doesn’t execute the source code but stitches modules and their dependencies together into a bundle. This can then be included in your HTML files.

Now, to expand the above cursory overview, let’s explore the main concepts webpack uses.

Webpack Main Concepts

Webpack has some main concepts which we need to understand clearly before digging in its practical implementation. Let’s examine them one by one:

  • Entry. The entry point is the module, which webpack uses to start building its internal dependency graph. From there, it determines which other modules and libraries that entry point depends on (directly and indirectly) and includes them in the graph until no dependency is left. By default, the entry property is set to ./src/index.js, but we can specify a different module (or even multiple modules) in the webpack configuration file.

  • Output. The output property instructs webpack where to emit the bundle(s) and what name to use for that file(s). The default value for this property is ./dist/main.js for the main bundle and ./dist for other generated files — such as images, for example. Of course, we can specify different values in the configuration depending on our needs.

  • Loaders. By default, webpack only understands JavaScript and JSON files. To process other types of files and convert them into valid modules, webpack uses loaders. Loaders transform the source code of non-JavaScript modules, allowing us to preprocess those files before they’re added to the dependency graph. For example, a loader can transform files from a CoffeeScript language to JavaScript or inline images to data URLs. With loaders we can even import CSS files directly from our JavaScript modules.

  • Plugins. Plugins are used for any other task that loaders can’t do. They provide us with a wide range of solutions about asset management, bundle minimization and optimization, and so on.

  • Mode. Typically, when we develop our application we work with two types of source code — one for the development build and one for the production build. Webpack allows us to set which one we want to be produced by changing the mode parameter to development, production or none. This allows webpack to use built-in optimizations corresponding to each environment. The default value is production. The none mode means that there won’t be used any default optimization options. To learn more about the options webpack uses in development and production mode, visit the mode configuration page.

How Webpack Works

In this section we’ll examine how webpack works. Even a simple project contains HTML, CSS and JavaScript files. Also, it can contains assets such as fonts, images, and so on. So, a typical webpack workflow would include setting up an index.html file with the appropriate CSS and JS links, and the necessary assets. Also, if you have many CSS and JS modules which depend on each other, they need to be optimized and properly combined in one unit ready for production.

To do all this, webpack relies on configuration. Although webpack 4 comes with reasonable defaults, for any non-trivial project you’ll need to provide a special configuration file webpack.config.js, which describes how the files and assets should be transformed and what kind of output should be generated. This file can quickly become quite monolithic, which makes it hard to understand how webpack does its job unless you know the main concepts behind its working.

Based on the provided configuration, webpack starts from the entry points and resolves each module it encounters while constructing the dependency graph. If a module contains dependencies, the process is performed recursively against each dependency until the traversal has completed. Then webpack bundles all project’s modules into a small number of bundles — usually, just one — to be loaded by the browser.

Getting Started

Note: you can find the files for our project in the GitHub repo.

Now that we have solid theoretical foundation, let’s implement it in practice.

To start, we’ll create a new directory and switch to it. Then we’ll initialize a new project:

mkdir learn-webpack
cd learn-webpack
npm init -y

Next, we need to install webpack and webpack CLI locally:

npm install webpack webpack-cli --save-dev

Now, the content of the generated package.json should be similar to the following:

{
  "name": "learn_webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.0"
  }
}

Besides bundling modules, webpack can be used as a simple task runner. We can create webpack tasks by including the name of our task followed by its instructions in the scripts section of the package,json file. Let’s try this now. Open package.json and change the scripts object to the following:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "dev": "webpack --mode development",
  "build": "webpack --mode production"
},

Within the scripts property, webpack allows us to reference locally installed npm packages by their names. We use that and the --mode flag to define dev and build tasks, which will run webpack in development (npm run dev) and production (npm run build) mode respectively.

Before we test the tasks we’ve just created, let’s create a src directory and put an index.js file in it so that it contains console.log("Hello webpack");. Now we can already to run the dev task to start webpack in development mode:

$ npm run dev

> learn_webpack@1.0.0 dev C:\Users\User\Webpack\learn_webpack
> webpack --mode development

Hash: 5bb3bdc1efd7b7f4b627
Version: webpack 4.30.0
Time: 226ms
Built at: 2019-04-16 17:48:32
  Asset     Size  Chunks             Chunk Names
main.js  3.8 KiB    main  [emitted]  main
Entrypoint main = main.js
[./src/index.js] 27 bytes {main} [built]

Great! It works as expected. But to verify that we get the correct output, we need to display the result in the browser. To do that, let’s create an index.html file in the dist directory:

<!doctype html>
<html>
  <head>
    <title>Getting Started</title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

Now, if we open the file in the browser, we should see the Hello webpack message in the console.

So far, so good. But writing our index.html file manually can be problematic in some cases. For example, if we change the name of our entry point, the generated bundle will be renamed, but our index.html file will still reference the old name. So, we’ll need to update our HTML file manually every time we rename an entry point or add new one. Fortunately, we can easily fix that with the html-webpack-plugin. Let’s install it now:

npm install html-webpack-plugin --save-dev

At this point, to activate the plugin, we need to create a webpack.config.js file in the root directory with the following content:

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      title: "Webpack Output",
    }),
  ],
};

As you can see, to activate a webpack plugin, we need to include it and then add it to the plugins array. If needed, we also pass options to the plugin.

Let’s run our build now to see what will happen:

$ npm run build

> learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack
> webpack --mode production

Hash: e56a796f5ccfebcc8270
Version: webpack 4.30.0
Time: 1088ms
Built at: 2019-04-16 20:44:47
    Asset       Size  Chunks             Chunk Names
index.html  183 bytes          [emitted]
  main.js  956 bytes       0  [emitted]  main
Entrypoint main = main.js
[0] ./src/index.js 27 bytes {0} [built]
Child html-webpack-plugin for "index.html":
    1 asset
    Entrypoint undefined = index.html
    [2] (webpack)/buildin/global.js 472 bytes {0} [built]
    [3] (webpack)/buildin/module.js 497 bytes {0} [built]
        + 2 hidden modules

Let’s open the index.html. As we can see, the plugin automatically creates an updated index.html file for us which uses the title option from the configuration:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack Output</title>
  </head>
  <body>
  <script type="text/javascript" src="main.js"></script></body>
</html>

Let’s now expand our project and specify custom names for the entry and output properties. In webpack.config.js we add the following before the plugins property:

entry: './src/app.js',
output: {
  filename: '[name].bundle.js',
  path: path.resolve(__dirname, 'dist')
},

Now, we’ll create an src/component.js file:

export default (text = "Hello webpack") => {
  const element = document.createElement("p");

  element.innerHTML = text;

  return element;
};

Next, we rename index.js to app.js to reflect our changes, and swap its content with the following:

import component from "./component";

document.body.appendChild(component());

Now, let’s run webpack in production mode:

$ npm run build

> learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack
> webpack --mode production

Hash: 9f78936f8a2a21061f0b
Version: webpack 4.30.0
Time: 1689ms
Built at: 2019-04-17 23:43:40
        Asset       Size  Chunks             Chunk Names
    index.html  190 bytes          [emitted]
main.bundle.js   1.04 KiB       0  [emitted]  main
Entrypoint main = main.bundle.js
[0] ./src/app.js + 1 modules 227 bytes {0} [built]
    | ./src/app.js 79 bytes [built]
    | ./src/component.js 148 bytes [built]
Child html-webpack-plugin for "index.html":
    1 asset
    Entrypoint undefined = index.html
    [2] (webpack)/buildin/global.js 472 bytes {0} [built]
    [3] (webpack)/buildin/module.js 497 bytes {0} [built]
        + 2 hidden modules

Let’s examine and clarify the information from the webpack output. Beginning from the top, we see the hash of the build, webpack version, and the time it took to execute the build. Next, we see the files generated in the dist directory (index.html and main.bundle.js). Below them, we see the entry module (app.js) and its dependency (component.js). The output after Child html-webpack-plugin for "index.html": is related to the internal work of the html-webpack-plugin and we can safely ignore it.

So now, in the dist folder, we have the newly generated bundle file main.bundle.js. If we open index.html in the browser, we should see Hello webpack displayed on the page. Also, if we check the source of index.html, we’ll see that the value of the src property in the script tag is updated to main.bundle.js.

The post A Beginner’s Guide to Webpack appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

It’s practically impossible to imagine any dashboard without graphs and charts. They present complex statistics quickly and effectively. Additionally, a good graph also enhances the overall design of your website.

In this article, I’ll show you some of the best JavaScript libraries for graphs / charts. These libraries will help you create beautiful and customisable charts for your future projects.

While most of the libraries are free and open source, some of them provide a paid version with additional features.

D3.js — Data-Driven Documents

When we think of charting today, D3.js is the first name that comes up. Being an open source project, D3.js definitely brings many powerful features that were missing in most of the existing libraries. Features like "Enter and Exit", powerful transitions and syntax familiarity with jQuery or Prototype make it one the best JavaScript libraries for charting. Charts in D3.js are rendered via HTML, SVG and CSS.

Unlike many other JavaScript libraries, D3.js doesn't ship with any pre-built charts out of the box. However, you can look at the list of graphs built with D3.js to get an overview.

D3.js doesn't work well with older browsers like IE8. You can always use plugins like aight plugin for cross browser compatibility.

Websites like NYTimes, Uber and Weather.com have used D3.js extensively in the past.

Google Charts

Google Charts is my go-to JavaScript library for creating charts easily. It provides many pre-built charts like area charts, bar charts, calendar charts, pie Charts, geo charts, and more.

Google charts also comes with various customization options that help in changing the look of the graph. Charts are rendered using HTML5/SVG to provide cross-browser compatibility and cross platform portability to iPhones, iPads, and Android. It also includes VML for supporting older IE versions.

Here's a great list of examples built using Google charts.

ChartJS

ChartJS provides beautiful flat designs for charts. It uses HTML5 canvas element for rendering. Support for older browsers like IE7/8 is added through polyfill.

ChartJS charts are responsive by default. They work well in mobiles and tablets. With 6 different types of core charts out of the box (core, bar, doughnut, radar, line, and polar area), ChartJS is definitely one of the most impressive open source charting libraries in recent times.

Chartist.js

Chartist.js provides beautiful responsive charts. Just like ChartJS, Chartist.js is also the product of the community that was frustrated by using highly priced JavaScript charting libraries. It uses SVG to render the charts. It can be controlled and customised through CSS3 media queries and Sass. Also, note that Chartist.js provides cool animations that will work only in modern browsers.

n3-charts

If you are an Angular developer, you will definitely find n3-charts extremely useful and interesting. n3-charts is built on top of D3.js and Angular. It provides various standard charts in the form of customisable Angular directives.

Checkout list of charts built using ns-charts.

Ember Charts

Ember Charts is another great open source repository built with D3.js and Ember.js. It provides time series, bar, pie, and scatter charts that are easily customisable. It uses SVG to render charts.

The post 18+ JavaScript Libraries for Creating Beautiful Charts appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Curious about all the buzz surrounding GraphQL, but not quite sure why you should be excited? You're in the right place! We'll shed some light on what GraphQL is and give you an opportunity for some hands-on experience.

Let's start by clearing the air and answering the $20,000 question: what is GraphQL? No, it's not an obscure function on your TI-89. It's a query language at heart — or query specification more accurately — that can be used to fetch data from just about any data source.

Better yet, it allows you to fetch the exact data you need — no more, no less — in a single network request. While that may not sound like the sexiest tech to come out of the Facebook factory of innovation, you may just find yourself pleasantly surprised at how useful it can be.

All that's needed is an Apollo server to act as our endpoint and a React app using the Apollo client to leverage any data within. We'll tackle the server first.

Getting Started with Apollo Server

To get our Apollo server started, create a folder called apollo-server in your favorite working directory. Next, enter that directory and run the following npm command — you do have npm and Node installed, right? — to get the Apollo framework in place:

The post Explore GraphQL with Apollo & React: Build a Superhero Database appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this post, we'll be introducing Nest.js for Angular developers. Nest.js is particularly interesting for them since it was heavily inspired by Angular and built for TypeScript. So what's Nest.js?

Nest.js is an open source MIT-licensed progressive Node framework, written in TypeScript and sharing many concepts with Angular. It's for the server side and can be used to build efficient, reliable and scalable web applications for the enterprise. It's built by Kamil Mysliwiec.

Nest.js combines the best concepts of Object Oriented Programming, Functional Programming and Functional Reactive Programming.

Nest.js has a plethora of features such as:

The post Introduction to Nest.js for Angular Developers appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Developers spend precious little time coding. Even if we ignore irritating meetings, much of the job involves basic tasks which can sap your working day:

  • generating HTML from templates and content files
  • compressing new and modified images
  • compiling Sass to CSS code
  • removing console and debugger statements from scripts
  • transpiling ES6 to cross-browser–compatible ES5 code
  • code linting and validation
  • concatenating and minifying CSS and JavaScript files
  • deploying files to development, staging and production servers.

Tasks must be repeated every time you make a change. You may start with good intentions, but the most infallible developer will forget to compress an image or two. Over time, pre-production tasks become increasingly arduous and time-consuming; you'll dread the inevitable content and template changes. It's mind-numbing, repetitive work. Wouldn’t it be better to spend your time on more profitable jobs?

If so, you need a task runner or build process.

That Sounds Scarily Complicated!

Creating a build process will take time. It's more complex than performing each task manually, but over the long term, you’ll save hours of effort, reduce human error and save your sanity. Adopt a pragmatic approach:

  • Automate the most frustrating tasks first.
  • Try not to over-complicate your build process. An hour or two is more than enough for the initial setup.
  • Choose task runner software and stick with it for a while. Don't switch to another option on a whim.

Some of the tools and concepts may be new to you, but take a deep breath and concentrate on one thing at a time.

Task Runners: the Options

Build tools such as GNU Make have been available for decades, but web-specific task runners are a relatively new phenomenon. The first to achieve critical mass was Grunt — a Node.js task runner which used plugins controlled (originally) by a JSON configuration file. Grunt was hugely successful, but there were a number of issues:

  1. Grunt required plugins for basic functionality such as file watching.
  2. Grunt plugins often performed multiple tasks, which made customisation more awkward.
  3. JSON configuration could become unwieldy for all but the most basic tasks.
  4. Tasks could run slowly because Grunt saved files between every processing step.

Many issues were addressed in later editions, but Gulp had already arrived and offered a number of improvements:

  1. Features such as file watching were built in.
  2. Gulp plugins were (mostly) designed to do a single job.
  3. Gulp used JavaScript configuration code that was less verbose, easier to read, simpler to modify, and provided better flexibility.
  4. Gulp was faster because it uses Node.js streams to pass data through a series of piped plugins. Files were only written at the end of the task.

Of course, Gulp itself isn't perfect, and new task runners such as Broccoli.js, Brunch and webpack have also been competing for developer attention. More recently, npm itself has been touted as a simpler option. All have their pros and cons, but Gulp remains the favorite and is currently used by more than 40% of web developers.

Gulp requires Node.js, but while some JavaScript knowledge is beneficial, developers from all web programming faiths will find it useful.

What About Gulp 4?

This tutorial describes how to use Gulp 3 — the most recent release version at the time of writing. Gulp 4 has been in development for some time but remains a beta product. It's possible to use or switch to Gulp 4, but I recommend sticking with version 3 until the final release.

Step 1: Install Node.js

Node.js can be downloaded for Windows, macOS and Linux from nodejs.org/download/. There are various options for installing from binaries, package managers and docker images, and full instructions are available.

Note for Windows users: Node.js and Gulp run on Windows, but some plugins may not install or run if they depend on native Linux binaries such as image compression libraries. One option for Windows 10 users is the new bash command-line, which solves many issues.

Once installed, open a command prompt and enter:

node -v

This reveals the version number. You're about to make heavy use of npm — the Node.js package manager which is used to install modules. Examine its version number:

npm -v

Note for Linux users: Node.js modules can be installed globally so they’re available throughout your system. However, most users will not have permission to write to the global directories unless npm commands are prefixed with sudo. There are a number of options to fix npm permissions and tools such as nvm can help, but I often change the default directory. For example, on Ubuntu/Debian-based platforms:

cd ~
mkdir .node_modules_global
npm config set prefix=$HOME/.node_modules_global
npm install npm -g

Then add the following line to the end of ~/.bashrc:

export PATH="$HOME/.node_modules_global/bin:$PATH"

Finally, update with this:

source ~/.bashrc
Step 2: Install Gulp Globally

Install Gulp command-line interface globally so the gulp command can be run from any project folder:

npm install gulp-cli -g

Verify Gulp has installed with this:

gulp -v
Step 3: Configure Your Project

Note for Node.js projects: you can skip this step if you already have a package.json configuration file.

Presume you have a new or pre-existing project in the folder project1. Navigate to this folder and initialize it with npm:

cd project1
npm init

You’ll be asked a series of questions. Enter a value or hit Return to accept defaults. A package.json file will be created on completion which stores your npm configuration settings.

Note for Git users: Node.js installs modules to a node_modules folder. You should add this to your .gitignore file to ensure they’re not committed to your repository. When deploying the project to another PC, you can run npm install to restore them.

For the remainder of this article, we'll presume your project folder contains the following sub-folders:

src folder: preprocessed source files

This contains further sub-folders:

  • html - HTML source files and templates
  • images — the original uncompressed images
  • js — multiple preprocessed script files
  • scss — multiple preprocessed Sass .scss files

build folder: compiled/processed files

Gulp will create files and create sub-folders as necessary:

  • html — compiled static HTML files
  • images — compressed images
  • js — a single concatenated and minified JavaScript file
  • css — a single compiled and minified CSS file

Your project will almost certainly be different but this structure is used for the examples below.

Tip: If you're on a Unix-based system and you just want to follow along with the tutorial, you can recreate the folder structure with the following command:

mkdir -p src/{html,images,js,scss} build/{html,images,js,css}
Step 4: Install Gulp Locally

You can now install Gulp in your project folder using the command:

npm install gulp --save-dev

This installs Gulp as a development dependency and the "devDependencies" section of package.json is updated accordingly. We’ll presume Gulp and all plugins are development dependencies for the remainder of this tutorial.

Alternative Deployment Options

Development dependencies are not installed when the NODE_ENV environment variable is set to production on your operating system. You would normally do this on your live server with the Mac/Linux command:

export NODE_ENV=production

Or on Windows:

set NODE_ENV=production

This tutorial presumes your assets will be compiled to the build folder and committed to your Git repository or uploaded directly to the server. However, it may be preferable to build assets on the live server if you want to change the way they are created. For example, HTML, CSS and JavaScript files are minified on production but not development environments. In that case, use the --save option for Gulp and all plugins, i.e.

npm install gulp --save

This sets Gulp as an application dependency in the "dependencies" section of package.json. It will be installed when you enter npm install and can be run wherever the project is deployed. You can remove the build folder from your repository since the files can be created on any platform when required.

Step 4: Create a Gulp Configuration File

Create a new gulpfile.js configuration file in the root of your project folder. Add some basic code to get started:

// Gulp.js configuration
var
  // modules
  gulp = require('gulp'),

  // development mode?
  devBuild = (process.env.NODE_ENV !== 'production'),

  // folders
  folder = {
    src: 'src/',
    build: 'build/'
  }
;

This references the Gulp module, sets a devBuild variable to true when running in development (or non-production mode) and defines the source and build folder locations.

ES6 note: ES5-compatible JavaScript code is provided in this tutorial. This will work for all versions of Gulp and Node.js with or without the --harmony flag. Most ES6 features are supported in Node 6 and above so feel free to use arrow functions, let, const, etc. if you're using a recent version.

gulpfile.js won't do anything yet because you need to …

Step 5: Create Gulp Tasks

On its own, Gulp does nothing. You must:

  1. install Gulp plugins, and
  2. write tasks which utilize those plugins to do something useful.

It's possible to write your own plugins but, since almost 3,000 are available, it's unlikely you'll ever need to. You can search using Gulp's own directory at gulpjs.com/plugins/, on npmjs.com, or search "gulp something" to harness the mighty power of Google.

Gulp provides three primary task methods:

  • gulp.task — defines a new task with a name, optional array of dependencies and a function.
  • gulp.src — sets the folder where source files are located.
  • gulp.dest — sets the destination folder where build files will be placed.

Any number of plugin calls are set with pipe between the .src and .dest.

The post An Introduction to Gulp.js appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Programming is not only about giving the computer instructions about how to accomplish a task, it’s also about communicating ideas in a precise way with other people, or even to your future self. Such communication can have multiple goals, maybe to share information or just to allow easier modifications—it’s hard to change something if you don’t understand it or if you don’t remember what you did long time ago. Documentation is key, either as simple comments in your code or as whole documents describing the overall functionality of a program.

When we write software we also need to make sure that the code has the intended functionality. While there are formal methods to define semantics, the easiest and quickest (but less rigorous) way is to put that functionality into use and see if it produces the expected results.

Most developers are familiar with these practices: code documentation as comments to make explicit the goal of a block of code, and a series of tests to make sure functions give the desired output.

But usually the documentation and testing is done in different steps, and by unifying these practices, we can offer a better experience for anyone involved in the development of a project. This article explores as simple implementation of a program to run JavaScript specifications that work for both documentation and testing.

We are going to build a command-line interface that finds all the specification files in a directory, extracts all the assertions found inside each specification and evaluates their result, finally showing the results of which assertions failed and which ones passed.

The Specification Format

Each specification file will export a single string from a template literal. The first line can be taken as the title of the specification. The template literal will allow us to embed JS expressions between the string and each expression will represent an assertion. To identify each assertion we can start the line with a distinctive character, in this case, we can use the combination of the bar character (|) and a dash (-), which resembles a turnstile symbol that can sometimes be found as a symbolic representation for logical assertions.

The following is an example with some explanations of its use:

The post How to Build Runnable JavaScript Specifications appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Single-page applications sometimes cop a little flack for their slow initial load. This is because traditionally, the server will send a large bundle of JavaScript to the client, which must be downloaded and parsed before anything is displayed on the screen. As you can imagine, as your app grows in size, this can become more and more problematic.

Luckily, when building a Vue application using Vue CLI (which uses webpack under the hood), there are a number of measures one can take to counteract this. In this article, I’ll demonstrate how make use of both asynchronous components and webpack’s code-splitting functionality to load in parts of the page after the app’s initial render. This will keep the initial load time to a minimum and give your app a snappier feel.

To follow this tutorial, you need a basic understanding of Vue.js and optionally Node.js.

Async Components

Before we dive into creating asynchronous components, let’s take a look at how we normally load a component. To do so, we’ll use a very simple message component:

<!-- Message.vue -->
<template>
  <h1>New message!</h1>
</template>

Now that we’ve created our component, let’s load it into our App.vue file and display it. We can just import the component and add it to the components option so we can use it in our template:

<!-- App.vue -->
<template>
  <div>
    <message></message>
  </div>
</template>

<script>
import Message from "./Message";
export default {
  components: {
    Message
  }
};
</script>

But what happens now? The Message component will be loaded whenever the application is loaded, so it’s included in the initial load.

This might not sound like a huge problem for a simple app, but consider something more complex like a web store. Imagine that a user adds items to a basket, then wants to check out, so clicks the checkout button which renders a box with all details of the selected items. Using the above method, this checkout box will be included in the initial bundle, although we only need the component when the user clicks the checkout button. It’s even possible that the user navigates through the website without ever clicking the checkout button, meaning that it doesn’t make sense to waste resources on loading this potentially unused component.

To improve the efficiency of the application, we can combine both lazy loading and code splitting techniques.

Lazy loading is all about delaying the initial load of a component. You can see lazy loading in action on sites like medium.com, where the images are loaded in just before they’re required. This is useful, as we don’t have to waste resources loading all the images for a particular post up front, as the reader might skip the article halfway down.

The code splitting feature webpack provides allows you to split your code into various bundles that can then be loaded on demand or in parallel at a later point in time. It can be used to load specific pieces of code only when they’re required or used.

Dynamic Imports

Luckily, Vue caters for this scenario using something called dynamic imports. This feature introduces a new function-like form of import that will return a Promise containing the requested (Vue) component. As the import is a function receiving a string, we can do powerful things like loading modules using expressions. Dynamic imports have been available in Chrome since version 61. More information about them can be found on the Google Developers website.

The code splitting is taken care of by bundlers like webpack, Rollup or Parcel, which understand the dynamic import syntax and create a separate file for each dynamically imported module. We’ll see this later on in our console’s network tab. But first, let’s take a look at the difference between a static and dynamic import:

// static import
import Message from "./Message";

// dynamic import
import("./Message").then(Message => {
  // Message module is available here...
});

Now, let’s apply this knowledge to our Message component, and we’ll get an App.vue component that looks like this:

<!-- App.vue -->
<template>
  <div>
    <message></message>
  </div>
</template>

<script>
import Message from "./Message";
export default {
  components: {
    Message: () => import("./Message")
  }
};
</script>

As you can see, the import() function will resolve a Promise that returns the component, meaning that we’ve successfully loaded our component asynchronously. If you take a look in your devtools’ network tab, you’ll notice a file called 0.js that contains your asynchronous component.

Conditionally Loading Async Components

Now that we have a handle on asynchronous components, let’s truly harvest their power by only loading them when they’re really needed. In the previous section of this article, I explained the use case of a checkout box that’s only loaded when the user hits the checkout button. Let’s build that out.

Project Setup

If you don’t have Vue CLI installed, you should grab that now:

npm i -g @vue/cli

Next, use the CLI to create a new project, selecting the default preset when prompted:

vue create my-store

Change into the project directory, then install the ant-design-vue library, which we’ll be using for styling:

cd my-store
npm i ant-design-vue

Next, import the Ant Design library in src/main.js:

import 'ant-design-vue/dist/antd.css'

Finally, create two new components in src/comonents, Checkout.vue and Items.vue:

touch src/components/{Checkout.vue,Items.vue}

The post Optimize the Performance of a Vue App with Async Components appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

A sales funnel is an online marketing tool that is built and designed to capture leads from traffic and convert them into customers. They tend to convert 20% to 50% higher than ordinary web pages. A sales funnel typically consists of opt-in pages, order forms, shopping carts, checkout pages and email marketing software. Building such a system is not a walk in the park.

The common way of building a sales funnel today is by purchasing a monthly subscription plan from a sales funnel builder platform. The most popular provider currently charges about $100 to $300. There are other affordable options. However, you may encounter limitations or technical challenges with any provider you work with — some more severe than others.

If you don't want to pay for a subscription plan, then you will have to build one yourself. Historically, coding your own funnel has been more expensive and time-consuming. However, we are living in 2019. The technology used by web developers today has improved immensely in the last 10 years.

It's easier and faster to build and deploy a web application. We have tons of third-party providers that allow integrations to their platforms via remote APIs. This allows us to easily implement heavy-duty features without having to write the code ourselves.

The benefits of owning your own funnel code means your business will be more resilient. You can easily switch servers if something doesn't work out with your provider. You can also easily scale up your online business without meeting major obstacles.

In this tutorial, I'll show you how to code your own simple sales funnel with Vue that will help you promote a product or service that you are selling to consumers. We'll build a simple squeeze page funnel for collecting leads for your email list.

Prerequisites

This article assumes that you have at least a solid grasp in:

You'll need to have a modern version of Node.js and the Vue CLI tool installed in your system. At the time of writing this article, Node v10.15.1 was the current LTS. The current Vue CLI version tool is v3.4.1. My personal recommendation is to use nvm to keep your Node.js environment up-to-date. To install the Vue.js CLI tool, execute the command:

npm install @vue/cli

The post How to Build a Sales Funnel with Vue.js appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Node.js makes it possible to write applications in JavaScript on the server. It's built on the V8 JavaScript runtime and written in C++ — so it's fast. Originally, it was intended as a server environment for applications, but developers started using it to create tools to aid them in local task automation. Since then, a whole new ecosystem of Node-based tools (such as Grunt, Gulp and Webpack) has evolved to transform the face of front-end development.

This popular article was updated on 08.06.2017 to reflect the current state of npm, as well as the changes introduced by the release of version 5.

To make use of these tools (or packages) in Node.js we need to be able to install and manage them in a useful way. This is where npm, the Node package manager, comes in. It installs the packages you want to use and provides a useful interface to work with them.

In this article I'm going to look at the basics of working with npm. I will show you how to install packages in local and global mode, as well as delete, update and install a certain version of a package. I'll also show you how to work with package.json to manage a project's dependencies. If you're more of a video person, why not sign up for SitePoint Premium and watch our free screencast: What is npm and How Can I Use It?.

But before we can start using npm, we first have to install Node.js on our system. Let's do that now...

Installing Node.js

Head to the Node.js download page and grab the version you need. There are Windows and Mac installers available, as well as pre-compiled Linux binaries and source code. For Linux, you can also install Node via the package manager, as outlined here.

For this tutorial we are going to use v6.10.3 Stable. At the time of writing, this is the current Long Term Support (LTS) version of Node.

Tip: You might also consider installing Node using a version manager. This negates the permissions issue raised in the next section.

Let's see where node was installed and check the version.

$ which node
/usr/bin/node
$ node --version
v6.10.3

To verify that your installation was successful let's give Node's REPL a try.

$ node
> console.log('Node is running');
Node is running
> .help
.break Sometimes you get stuck, this gets you out
.clear Alias for .break
.exit  Exit the repl
.help  Show repl options
.load  Load JS from a file into the REPL session
.save  Save all evaluated commands in this REPL session to a file
> .exit

The Node.js installation worked, so we can now focus our attention on npm, which was included in the install.

$ which npm
/usr/bin/npm
$ npm --version
3.10.10
Node Packaged Modules

npm can install packages in local or global mode. In local mode it installs the package in a node_modules folder in your parent working directory. This location is owned by the current user. Global packages are installed in {prefix}/lib/node_modules/ which is owned by root (where {prefix} is usually /usr/ or /usr/local). This means you would have to use sudo to install packages globally, which could cause permission errors when resolving third-party dependencies, as well as being a security concern. Lets change that:

Time to manage those packages Changing the Location of Global Packages

Let's see what output npm config gives us.

$ npm config list
; cli configs
user-agent = "npm/3.10.10 node/v6.10.3 linux x64"

; userconfig /home/sitepoint/.npmrc
prefix = "/home/sitepoint/.node_modules_global"

; node bin location = /usr/bin/nodejs
; cwd = /home/sitepoint
; HOME = /home/sitepoint
; "npm config ls -l" to show all defaults.

This gives us information about our install. For now it's important to get the current global location.

$ npm config get prefix
/usr

This is the prefix we want to change, so as to install global packages in our home directory. To do that create a new directory in your home folder.

$ cd ~ && mkdir .node_modules_global
$ npm config set prefix=$HOME/.node_modules_global

With this simple configuration change, we have altered the location to which global Node packages are installed. This also creates a .npmrc file in our home directory.

$ npm config get prefix
/home/sitepoint/.node_modules_global
$ cat .npmrc
prefix=/home/sitepoint/.node_modules_global

We still have npm installed in a location owned by root. But because we changed our global package location we can take advantage of that. We need to install npm again, but this time in the new user-owned location. This will also install the latest version of npm.

$ npm install npm --global
└─┬ npm@5.0.2
  ├── abbrev@1.1.0
  ├── ansi-regex@2.1.1
....
├── wrappy@1.0.2
└── write-file-atomic@2.1.0

Finally, we need to add .node_modules_global/bin to our $PATH environment variable, so that we can run global packages from the command line. Do this by appending the following line to your .profile, .bash_profileor .bashrc and restarting your terminal.

export PATH="$HOME/.node_modules_global/bin:$PATH"

Now our .node_modules_global/bin will be found first and the correct version of npm will be used.

$ which npm
/home/sitepoint/.node_modules_global/bin/npm
$ npm --version
5.0.2

The post A Beginner’s Guide to npm — the Node Package Manager appeared first on SitePoint.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

This article was created in partnership with Sencha. Thank you for supporting the partners who make SitePoint possible.

React is a collection of tools and libraries that are independent of each other, which can be daunting for React developers with a job to do. The many tools grants plenty of freedom because you can shop around for the best ones for the job at hand. In React, there are many ways to solve a problem so knowing more than a few tools is a good idea. There are tools that are better at certain problems than others, it all depends on the context. Below is a list of tools I find useful in a good sized React project, some are newer than others and some solve a specific problem when working with React - but all of them I've found helpful.

For each React tool, I’ll provide a short summary with basic information before diving a bit deeper with cool things it can do and my thoughts. Keep in mind all these tools are subject to change.

The post 9 Helpful Tools for React Development appeared first on SitePoint.

Read Full Article

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview