跟随,学习,进步

SitePoint

SitePoint – Learn HTML, CSS, JavaScript, PHP, Ruby & Responsive Design

https://www.sitepoint.com
转到作者网站

SitePoint Premium New Releases: Clojure, npm, Gulp, Django & More

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them. Professional Clojure Designed for professional devs, this book explains how to parse the difference between functional and object-oriented programming, how to understand Clojure performance and capabilities, how to develop reactive web pages using ClojureScript, and how to adopt an REPL-driven development workflow. Read Professional Clojure. A Beginner’s Guide to npm, the Node Package Manager Learn how to use npm, the command-line tool for interacting with a huge repository of Node.js projects. Discover how to install packages in local and global mode, as well as delete, update and install a certain version of a package. You'll also see how how to manage a project’s dependencies. Read A Beginner’s Guide to npm, the Node Package Manager. Django 2 Web Development Cookbook Third Edition Create fast, robust and secure web apps with the Django Web Framework and Python 3.6. Discover solutions to a variety of web app scenarios. Understand URL routing, models, forms, templates, and RESTful services with Django 2.14. Test, deploy, and scale your web apps efficiently with AWS. Read Django 2 Web Development Cookbook Third Edition. An Introduction to Gulp.js In this guide, we'll introduce Gulp.js. We'll start out by installing Gulp and using it to carry out some basic tasks, such as compressing images, and then move on to using it for more advanced tasks, like populating a database. Read An Introduction to Gulp.js. Handbook of Usability Testing This book digs into how to make products user-friendly, with guidelines on testing, factors that limit usability, choosing and training test moderators, collecting and reviewing data, reporting results and making recommendations, user-centered design principles and practices, and much more. Read Handbook of Usability Testing. And More to Come… We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. And don't forget: if you haven't checked out our offering yet, take our 7 day free trial for a spin. The post SitePoint Premium New Releases: Clojure, npm, Gulp, Django & More appeared first on SitePoint.


Explore GraphQL with Apollo & React: Build a Superhero Database

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.


SitePoint Premium New Releases: Git, Cybersecurity, DevOps + More

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them. Professional Git This book gets you into the Git mindset, explaining the basic Git model and overall workflow, the Git versions of common source management concepts and commands, how to track changes, work with branches, and take advantage of Git's full functionality, and how to avoid trip-ups and missteps. Read Professional Git. WordPress Plugin Development Cookbook This book presents detailed, step-by-step recipes, explanations and code examples for creating WordPress 4.x plugins. Learn how to extend WordPress, how to use the WordPress plugin API, and how to mold WordPress to your project's needs. Read WordPress Plugin Development Cookbook. Cybersecurity Essentials A comprehensive introduction to cybersecurity concepts and practices, with expert coverage of essential topics required for entry-level cybersecurity certifications. Learn security and surveillance fundamentals, how to secure and protect remote access, how to identify threats and form an effective defense. Read Cybersecurity Essentials. The Profitable Side Project Handbook Do you dream of being able to earn money while you sleep? Of seeing sales come in while you are out for dinner? Of creating a great product that is sustainable as a real, profitable business? This book will help you to launch your own revenue generating side project. Read The Profitable Side Project Handbook. Hands-On DevOps with Vagrant Use Vagrant to easily build complete development environments. Implement DevOps with Vagrant effectively. Integrate Vagrant with different tools such as Puppet, Chef, and Docker. Manage infrastructure with a practical approach. Read Hands-On DevOps with Vagrant. And More to Come… We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. If you're not a member yet, check out our library for $14.99/month. The post SitePoint Premium New Releases: Git, Cybersecurity, DevOps + More appeared first on SitePoint.


6 Collaborative Coding Tools for Remote Pair Programming

Fifteen years ago, most online collaboration and remote work involved email threads, Skype calls, and endlessly re-zipping projects for sharing after each iteration. Things have changed a lot — most things for better (Google Docs!) and some things for worse (always-on messaging). Either way, it's fair to say that a lot of the friction has been removed from remote work. One traditionally high friction area has been cracking real-time code collaboration. But that's been changing in recent years as developers working on the world's top code editors have put forward their solutions. Whether you work on a distributed team and need collaborative coding tools to serve you every day, or just need something for the occasional problem-solving session with a friend, you'll find something you can use here. 1. Visual Studio Live Share Visual Studio Live Share is Microsoft's own real-time collaborative development solution for Visual Studio and Visual Studio Code. Live Share allows teams to collaborate on a shared codebase easily — nobody needs to clone a repo, and everyone can use their own development environment. Each person can perform actions like navigating between files, making changes to code, selecting text, and see them reflected for everyone immediately. Live Share shares everything from files to terminals and audio, offers features for collaborative debugging, and is free. If you're already a VS Code user, this choice is a no-brainer. While you're at it, check out our VS Code extension recommendations for JavaScript developers. 2. Teletype for Atom The post 6 Collaborative Coding Tools for Remote Pair Programming appeared first on SitePoint.


Introduction to Nest.js for Angular Developers

In this post, we'll be introducing Nest.js for Angular developers. Nest.js is particularly interesting for them since it was heavy 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.


Build a Slack App in 10 Minutes with MongoDB Stitch

This article was originally published on MongoDB. Thank you for supporting the partners who make SitePoint possible. Slack is not only the fastest growing startup in history, but it's also an app by the same name and one of the most popular communication tools in use today. We use it extensively at MongoDB to foster efficient communications between teams and across the company. We're not alone. It seems like every developer I encounter uses it in their company as well. One interesting thing about Slack (and there are many) is its extensibility. There are several ways you can extend Slack. Building chatbots, applications that interface with the communication service and extending Slack through the introduction of additional commands called "slash commands" that enable Slack users to communicate with external services. In this article, we'll build a simple slash command that enables users to store and retrieve data in and from a MongoDB database. I'm always finding interesting information on the internet that I want to share with my team members so let's build an application we'll call URL Stash that will store interesting URLs for later retrieval via a Slack slash command. Now, follow along in the video below or skip over the video and read on for the details. https://www.youtube.com/watch?v=FLSvZ2WmYzc Create a Slack App Start by logging into your slack team, or you can create a new one for testing. Visit the Slack API Console to create a new Slack App. The post Build a Slack App in 10 Minutes with MongoDB Stitch appeared first on SitePoint.


An Introduction to Gulp.js

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: Grunt required plugins for basic functionality such as file watching. Grunt plugins often performed multiple tasks, which made customisation more awkward. JSON configuration could become unwieldy for all but the most basic tasks. 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: Features such as file watching were built in. Gulp plugins were (mostly) designed to do a single job. Gulp used JavaScript configuration code that was less verbose, easier to read, simpler to modify, and provided better flexibility. 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: install Gulp plugins, and 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.


SitePoint Premium New Releases: Docker, Redux, & Interviews

We're working hard to keep you on the cutting edge of your field with SitePoint Premium. We've got plenty of new books to check out in the library — let us introduce you to them. Learning Docker - Second Edition Docker lets you create, deploy, and manage scalable app containers across multiple platforms. Learn how to package apps and build, ship, and scale containers. Delve into microservice architecture. Explore real-world examples of securing and managing Docker containers. Read Learning Docker - Second Edition. Programming Interviews Exposed With up-to-date advice on how to succeed in programming job interviews, this book discusses what interviewers need to hear, approaching phone screens with non-technical recruiters, examining common interview problems and tests, demonstrating your skills verbally, in contests, on GitHub, and more. Read Programming Interviews Exposed. Learning Redux With Redux, build consistent web apps that run in different environments (client, server and native), and are easy to test, by centralizing the state of your app. Take your web apps to the next level by combining the power of Redux with other frameworks such as React and Angular. Read Learning Redux. And More to Come… We're releasing new content on SitePoint Premium almost every day, so we'll be back next week with the latest updates. If you're not a member yet, check out our library for $14.99/month. The post SitePoint Premium New Releases: Docker, Redux, & Interviews appeared first on SitePoint.


How to Build Runnable JavaScript Specifications

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.


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.


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.


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.


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.


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.


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.


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.


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.


The Top 12 Multipurpose WordPress Themes to Choose in 2019

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible. Some WordPress users tend to avoid using multipurpose themes. They do so for reasons that would seem to make common sense. They subscribe to a popular saying – "jack of all trades, master of none." Here, anything designed to do everything won't do some, if any, of them particularly well. There are, of course, some multipurpose or all-in-one design tools that simply can't get the job done. Some may be poorly coded or have other faults. But there are plenty that make excellent choices for building almost any type of website. If there's a problem, it's that there are too many good ones. Finding a responsive theme that fits your needs can be a challenge. Searching for an alternative to plowing through a whole host of multipurpose themes? Consider checking out this list of our 12 favorite multipurpose themes for 2019. Starting with the popular… The post The Top 12 Multipurpose WordPress Themes to Choose in 2019 appeared first on SitePoint.


Fetching Data from a Third-party API with Vue.js and Axios

More often than not, when building your JavaScript application, you’ll want to fetch data from a remote source or consume an API. I recently looked into some publicly available APIs and found that there’s lots of cool stuff that can be done with data from these sources. With Vue.js, you can literally build an app around one of these services and start serving content to users in minutes. I’ll demonstrate how to build a simple news app that will show the top news articles of the day allow users to filter by their category of interest, fetching data from the New York Times API. You can find the complete code for this tutorial here. Here’s what the final app will look like: To follow along with this tutorial, you’ll need a very basic knowledge of Vue.js. You can find a great “getting started” guide for that here. I’ll also be using ES6 Syntax, and you can get a refresher on that here. Project Structure We’ll keep things very simple by limiting ourselves to just 2 files: ./app.js ./index.html app.js will contain all the logic for our app, and the index.html file will contain our app’s main view. We’ll start off with some basic markup in index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>The greatest news app ever</title> </head> <body> <div class="container" id="app"> <h3 class="text-center">VueNews</h3> </div> </body> </html> Next, include Vue.js and app.js at the bottom of index.html, just before the closing </body> tag: <script src="https://unpkg.com/vue"></script> <script src="app.js"></script> Optionally, Foundation can be included, to take advantage of some pre-made styles and make our view look a bit nicer. Include this within the <head> tag: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css"> Creating a Simple Vue App First, we’ll create a new Vue instance on the element div#app, and mock the response from the news API using some test data: // ./app.js const vm = new Vue({ el: '#app', data: { results: [ {title: "the very first post", abstract: "lorem ipsum some test dimpsum"}, {title: "and then there was the second", abstract: "lorem ipsum some test dimsum"}, {title: "third time's a charm", abstract: "lorem ipsum some test dimsum"}, {title: "four the last time", abstract: "lorem ipsum some test dimsum"} ] } }); We tell Vue what element to mount on, via the el option, and specify what data our app would be using via the data option. To display this mock data in our app view, we can write this markup inside the #app element: <!-- ./index.html --> <div class="columns medium-3" v-for="result in results"> <div class="card"> <div class="card-divider"> {{ result.title }} </div> <div class="card-section"> <p>{{ result.abstract }}.</p> </div> </div> </div> The v-for directive is used for rendering our list of results. We also use double curly braces to show the contents of each of them. Note: you can read more on the Vue Template Syntax here. We now have the basic layout working: Fetching Data from the API To make use of the NYTimes API, you’ll need to get an API key. So if you don’t already have one, head over to their signup page and register to get an API key for the Top Stories API. Making Ajax Requests and Handling Responses Axios is a promise-based HTTP client for making Ajax requests, and will work great for our purposes. It provides a simple and rich API. It’s quite similar to the fetch API, but without the need to add a polyfill for older browsers, and some other subtleties. Note: previously, vue-resource was commonly used with Vue projects, but it has been retired now. Including axios: <!-- ./index.html --> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> Now we can make a request to get a list of top stories from the home section, once our Vue app is mounted: // ./app.js const vm = new Vue({ el: '#app', data: { results: [] }, mounted() { axios.get("https://api.nytimes.com/svc/topstories/v2/home.json?api-key=your_api_key") .then(response => {this.results = response.data.results}) } }); Remember: replace your_api_key with your actual API key obtained from the NYT Dev Network area. Now we can see the news feed on our app homepage. Don’t worry about the distorted view; we’ll get to that in a bit: The response from the NYT API looks like this, via Vue devtools: The post Fetching Data from a Third-party API with Vue.js and Axios appeared first on SitePoint.


7 Cross-Browser Testing Tools You Need in 2019

First off, what is cross-browser testing? Cross-browser testing is the formality of testing web applications and websites in all of the common web browsers that users use today — this ensures that we deliver a consistent user experience everywhere, and not just the web browser that takes our fancy. Here are some of the things to look out for: Code validation: do some browsers report code errors? Performance: is the website slow, or even causing crashes? Responsive design: is the design consistently responsive? UI inconsistencies: are there any other design flaws? Other strange behaviours: anything else simply not working? What happens if I don’t test? Inconsistencies are actually very normal. Fact is, all web browsers behave and render websites a little differently, and some browsers might not even support the features we originally aimed to utilize; and when these inconsistencies appear, it can have a direct impact on our revenue (among other things). Let’s take eCommerce for example. 69.89% of checkouts are abandoned, and 17% of those are attributed to website errors and crashes. Assuming that a business would accrue half a million sales annually, that’s 59,407 sales lost due to errors and crashes that could have been thwarted by cross-browser testing. Which browsers should I test on? Since Microsoft announced they’d be ditching their own EdgeHTML and Chakra engines in favor of the widely-adopted Blink and V8 engines, this means many of the major browsers today offer similar levels of code compatibility. While this is a step back in terms of healthy competition, it does mean that if a website works in Google Chrome, it’ll most likely work in Brave, Opera, and soon-to-be Microsoft Edge. That combined with the fact that even Microsoft has instructed us to stop using Internet Explorer, cross-browser testing is easier than it’s ever been before, with only Safari and Firefox using their own engines. Technically, the web browsers we should be supporting today are the ones that our users and customers are using, information that’s easy enough to find using Google Analytics or some other kind of web analytics tracking software. But if you don’t have that kind of data available, here are the worldwide statistics*: Chrome: 61.75% Safari: 15.12% Firefox: 4.92% UC: 4.22% Opera: 3.15% Internet Explorer: 2.8% Samsung Internet: 2.74% Microsoft Edge: 2.15% *As of November 2018. Also, bear in mind that there are multiple releases of each web browser across multiple OSs. Sound scary? Not really, but it is boring as heck to be testing websites on all of them! Luckily, there are a number of excellent cross-browser testing tools available, so today we’re going to take a look at 7 of the best ones. The post 7 Cross-Browser Testing Tools You Need in 2019 appeared first on SitePoint.