SitePoint

Optimize the Performance of a Vue App with Async Components 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. Apr 18 How to Build a Sales Funnel with Vue.js 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: Modern JavaScript ES6+ A beginner's knowledge in Vue.js 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. Apr 17 How to Build a Stunning Portfolio Website as a Web Developer This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible. In your role as a professional web developer, you're up for just about any website-building challenge. But, building a creative website portfolio for your own services isn't something you're accustomed to. As much as you love web development, you've probably never thought of it as being a particularly sexy or creative profession. The truth is, it's not all that difficult to put an eye-grabbing portfolio together rather easily when you're armed with the right tools, and you have a selection of inspiring and relevant concepts to choose from. Here are 8 powerful ideas, together with 32 examples, to inspire you and enable you to promote your services on your own stunning portfolio website. The post How to Build a Stunning Portfolio Website as a Web Developer appeared first on SitePoint. Apr 16 A Beginner’s Guide to npm — the Node Package Manager 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. Apr 16 9 Helpful Tools for React Development 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. Apr 15 Getting up and Running with the Vue.js 2.0 Framework This article was updated in November 2018, primarily to bring the tooling section up to date. As soon as the popular JavaScript framework Vue.js released v2, I was eager to give it a spin and see what it’s like to work with. As someone who’s pretty familiar with Angular and React, I was looking forward to seeing the similarities and differences between them and Vue. Vue 2 sports excellent performance stats, a relatively small payload (the bundled runtime version of Vue weighs in at 30KB once minified and gzipped), along with updates to companion libraries like vue-router and Vuex, the state management library for Vue. There’s far too much to cover in just one article, but keep an eye out for some later articles where we’ll look more closely at various libraries that couple nicely with the core framework. Inspiration from Other Libraries As we go through this tutorial, you’ll see many features that Vue has that are clearly inspired by other frameworks. This is a good thing; it’s great to see new frameworks take some ideas from other libraries and improve on them. In particular, you’ll see Vue’s templating is very close to Angular’s, but its components and component lifecycle methods are closer to React’s (and Angular’s, as well). One such example of this is that, much like React and nearly every framework in JavaScript land today, Vue uses the idea of a virtual DOM to keep rendering efficient. Vue uses a fork of snabbdom, one of the more popular virtual DOM libraries. The Vue site includes documentation on its Virtual DOM rendering, but as a user all you need to know is that Vue is very good at keeping your rendering fast (in fact, it performs better than React in many cases), meaning you can rest assured you’re building on a solid platform. Components, Components, Components Much like other frameworks these days, Vue’s core building block is the component. Your application should be a series of components that build on top of each other to produce the final application. Vue.js goes one step further by suggesting (although not enforcing) that you define your components in a single .vue file, which can then be parsed by build tools (we’ll come onto those shortly). Given that the aim of this article is to fully explore Vue and what it feels like to work with, I’m going to use this convention for my application. A Vue file looks like so: <template> <p>This is my HTML for my component</p> </template> <script> export default { // all code for my component goes here } </script> <style scoped> /* CSS here * by including `scoped`, we ensure that all CSS * is scoped to this component! */ </style> Alternatively, you can give each element a src attribute and point to a separate HTML, JS or CSS file respectively if you don’t like having all parts of the component in one file. Setting Up a Project Whilst the excellent Vue CLI exists to make setting up a full project easy, when starting out with a new library I like to do it all from scratch so I get more of an understanding of the tools. These days, webpack is my preferred build tool of choice, and we can couple that with the vue-loader plugin to support the Vue.js component format that I mentioned previously. We’ll also need Babel and the env preset, so we can write all our code using modern JavaScript syntax, as well as the webpack-dev-server, which will update the browser when it detects a file change. Let’s initialize a project and install the dependencies: mkdir vue2-demo-project cd vue2-demo-project npm init -y npm i vue npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev Then create the initial folders and files: mkdir src touch webpack.config.js src/index.html src/index.js The project structure should look like this: . ├── package.json ├── package-lock.json ├── src │ ├── index.html │ └── index.js └── webpack.config.js Now let’s set up the webpack configuration. This boils down to the following: Tell webpack to use the vue-loader for any .vue files Tell webpack to use Babel and the env preset for any .js files Tell webpack to generate an HTML file for the dev-server to serve, using src/index.html as a template: //webpack.config.js const VueLoaderPlugin = require('vue-loader/lib/plugin') const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new VueLoaderPlugin(), new HtmlWebPackPlugin({ template: "./src/index.html" }) ] } Finally, we’ll add some content to the HTML file and we’re ready to go! <!-- src/index.html --> <!DOCTYPE html> <html> <head> <title>My Vue App</title> </head> <body> <div id="app"></div> </body> </html> We create an empty div with the ID of app, as this is the element that we’re going to place our Vue application in. I always prefer to use a div, rather than just the body element, as that lets me have control over the rest of the page. Writing Our First Vue.js App We’re going to stay true to every programming tutorial ever and write a Vue application that puts “Hello, World!” onto the screen before we dive into something a bit more complicated. Each Vue app is created by importing the library and then instantiating a new Vue instance: import Vue from 'vue' const vm = new Vue({ el: '#app', }) We give Vue an element to render onto the page, and with that, we’ve created a Vue application! We pass a selector for the element that we want Vue to replace with our application. This means when Vue runs it will take the div#app that we created and replace it with our application. The reason we use the variable name vm is because it stands for “View Model”. Although not strictly associated with the “Model View View-Model” (MVVM) pattern, Vue was inspired in part by it, and the convention of using the variable name vm for Vue applications has stuck. Of course, you can call the variable whatever you’d like! So far, our application isn’t doing anything, though, so let’s create our first component, App.vue, that will actually render something onto the page. Vue doesn’t dictate how your application is structured, so this one is up to you. I ended up creating one folder per component, in this case App (I like the capital letter, signifying a component), with three files in it: index.vue script.js style.css mkdir src/App touch src/App/{index.vue,script.js,style.css} The file structure should now be: . ├── package.json ├── package-lock.json ├── src │ ├── App │ │ ├── index.vue │ │ ├── srcipt.js │ │ └── style.css │ ├── index.html │ └── index.js └── webpack.config.js App/index.vue defines the template, then imports the other files. This is in keeping with the structure recommended in the What About Separation of Concerns? section of Vue’s docs. <!-- src/App/index.vue --> <template> <p>Hello, World!</p> </template> <script src="./script.js"></script> <style scoped src="./style.css"></style> I like calling it index.vue, but you might want to call it app.vue too so it’s easier to search for. I prefer importing App/index.vue in my code versus App/app.vue, but again you might disagree, so feel free to pick whatever you and your team like best. For now, our template is just <p>Hello, World!</p>, and I’ll leave the CSS file blank. The main work goes into script.js, which looks like so: export default { name: 'App', data() { return {} }, } Doing this creates a component which we’ll give the name App, primarily for debugging purposes, which I’ll come to later, and then defines the data that this component has and is responsible for. For now, we don’t have any data, so we can just tell Vue that by returning an empty object. Later on, we’ll see an example of a component using data. Now we can head back into src/index.js and tell the Vue instance to render our App component: import Vue from 'vue' import AppComponent from './App/index.vue' const vm = new Vue({ el: '#app', components: { app: AppComponent, }, render: h => h('app'), }) Firstly, we import the component, trusting webpack and the vue-loader to take care of parsing it. We then declare the component. This is an important step: by default, Vue components are not globally available. Each component must have a list of all the components they’re going to use, and the tag that it will be mapped to. In this case, because we register our component like so: components: { app: AppComponent, } This means that in our templates we’ll be able to use the app element to refer to our component. Finally, we define the render function. This function is called with a helper — commonly referred to as h — that’s able to create elements. It’s not too dissimilar to the React.createElement function that React uses. In this case, we give it the string 'app', because the component we want to render is registered as having the tag app. More often than not (and for the rest of this tutorial) we won’t use the render function on other components, because we’ll define HTML templates. But the Vue.js guide to the render function is worth a read if you’d like more information. Once we’ve done that, the final step is to create an npm script in package.json: "scripts": { "start": "webpack-dev-server --mode development --open" }, Now, run npm run start. Your default browser should open at http://localhost:8080/ and you should see “Hello, World!” on the screen. Try editing src/index.vue to change the message to something else. If all has gone correctly, webpack-dev-server should refresh the page to reflect your changes. Yay! We’re up and running with Vue.js. The post Getting up and Running with the Vue.js 2.0 Framework appeared first on SitePoint. Apr 15 Function Composition in JavaScript with Array.prototype.reduceRight Functional programming in JavaScript has rocketed in popularity over the last few years. While a handful of its regularly-promoted tenets, such as immutability, require runtime workarounds, the language's first-class treatment of functions has proven its support of composable code driven by this fundamental primitive. Before covering how one can dynamically compose functions from other functions, let's take a brief step back. What is a Function? Effectively, a function is a procedure that allows one to perform a set of imperative steps to either perform side effects or to return a value. For example: function getFullName(person) { return `${person.firstName} ${person.surname}`; } When this function is invoked with an object possessing firstName and lastName properties, getFullName will return a string containing the two corresponding values: const character = { firstName: 'Homer', surname: 'Simpson', }; const fullName = getFullName(character); console.log(fullName); // => 'Homer Simpson' It's worth noting that, as of ES2015, JavaScript now supports arrow function syntax: const getFullName = (person) => { return `${person.firstName} ${person.surname}`; }; Given our getFullName function has an arity of one (i.e. a single argument) and a single return statement, we can streamline this expression: const getFullName = person => `${person.firstName} ${person.surname}`; These three expressions, despite differing in means, all reach the same end in: creating a function with a name, accessible via the name property, of getFullName accepting a sole parameter, person returning a computed string of person.firstName and person.lastName, both being separated by a space Combining Functions via Return Values As well as assigning function return values to declarations (e.g. const person = getPerson();), we can use them to populate the parameters of other functions, or, generally speaking, to provide values wherever JavaScript permits them. Say we have respective functions which perform logging and sessionStorage side effects: The post Function Composition in JavaScript with Array.prototype.reduceRight appeared first on SitePoint. Apr 10 4 Ways to Grow Your Online Brand by Combining Content & Commerce For years, one of the most significant challenges to scaling a WordPress site was due to the clunky ecommerce options. Sure, you could use platforms like Shopify, but those take your customers offsite and don't scale well or integrate easily with WordPress. In addition, traditional ecommerce solutions focus on selling, not content. With 30% of all businesses using WordPress (making it the most widely used content management system on the planet), that left a huge hole in the ecommerce market. Until now. With the latest addition of BigCommerce for WordPress, growing an online brand using headless commerce solutions is easier than ever. You no longer have to choose between selling products or focusing on content marketing. Now, you can match different ecommerce sites and platforms with content-driven strategies to create a blog that gets traffic--and makes sales. So, how do you do it? Here are four strategies for building an online brand by combining the power of content marketing with advanced ecommerce tools. Develop Your Blog with Niche Content to Attract Leads Too many people think content market is squishy; they think it is untrackable, unscalable, and incapable of driving sales. Those people are wrong. Here's why. Customers enjoy reading relevant content. It makes them feel closer and more positive about a brand. Consider these stats from Demand Metric: Image source Need more proof? How about the fact that 60% of people are inspired to seek out a product after reading content about it? With over 4 million blog posts published daily, it’s a sign that content marketing is here to stay. Content sells, plain and simple. How Niche Content Can Help You Drive Leads &Amp; Sell Instead of creating widely popular content, which is likely to get lost in the ever-growing expanse of the internet, develop and market to a small, niche audience. Here is how niche marketing helps you sell: Niche marketing is about understanding who your audience is and taking the time to build a strong, trusting relationship. For instance, take this free piece of content that Freshdesk gives their readers, a customer service resume template: Image source This provides instant value for people in the field of customer service, perfectly relating to the products they sell. Better content like this customer service resume value-add means your competition is less likely to be able to draw your customers away with, for example, slightly lower prices. Long term, you become a trusted expert; a big fish in a small pond. And your customers become brand loyal and enter your sales funnel. Let’s look deeper into niche ecommerce content. What Niche Ecommerce Content Looks Like So, what does good niche content look like in the commerce field? Are we talking detailed products descriptions, quirky headlines, flawless grammar? Nope, there is more to it than that. Good content should always be focused on what is useful to your audience. You can use social media analytics tools to track engagement and tailor your site messaging to match. In the ecommerce field this might mean: Educating your audience by describing a little-known or little-understood feature. Showing them how to complete a challenging task. Giving a list of resources in your industry. Gift guides for hard to the hard to shop for. The right type of niche SEO content will depend upon your industry, of course. So, let's look at a few examples of niche content marketing done right. Mighty Nest Mighty Nest is a socially conscious ecommerce store dedicated to helping people find eco-friendly, green, and minimal waste products. Their content addresses the questions and problems many people have when looking for safer alternatives. Take a look at this post, titled "The Essential Guide to GOOD Skincare Ingredients." This piece blends education — "Here's why these chemicals are bad for your skin." — with product recommendations aimed at a niche audience: people who are looking for healthy skin care alternatives. Image source It won't reach the masses, but instead focuses on those who care about natural skin care products. Grovemade Here is another example, from company Grovemade. They design, manufacture, and sell beautifully simple items made from natural materials including electronic charging pads, speakers, pen holders, and watches. The post 4 Ways to Grow Your Online Brand by Combining Content & Commerce appeared first on SitePoint. Apr 10