跟随,学习,进步

SitePoint

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

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

SitePoint Premium New Releases: SSGs, Interaction Design, Node & Vue

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. An Introduction to Hexo In this guide we'll present Hexo, an open-source static site generator suitable for building blogs and documentation websites. We'll cover installation, working with layouts, generating posts and providing content, customizing and installing third-party themes, and deploying to Heroku. ➤ Read An Introduction to Hexo. About Face This essential interaction design guide examines mobile apps, touch interfaces and screen size considerations, examining goal-directed design methodology, product design methods, design for mobile platforms and consumer electronics, contemporary interfaces, interface recommendations, and much more. ➤ Read About Face. Drupal 8 Development Cookbook Second Edition Discover the enhanced content authoring experience that comes with Drupal 8 and how to customize it. Take advantage of multilingual tools for providing an internationalized website. Learn how to deploy from development, staging, and production with Drupal's config management system. ➤ Read Drupal 8 Development Cookbook Second Edition. A Beginner’s Guide to Creating a Static Website with Hugo This tutorial describes how to use Hugo, a static site generator (SSG) written in Go. Hugo boasts rich features, is very quick thanks to Go, and has lots of third-party themes, an active community, and detailed documentation. ➤ Read A Beginner’s Guide to Creating a Static Website with Hugo. RESTful Web API Design with Node.js 10 - Third Edition Design and implement scalable and maintainable RESTful solutions with Node.js 10 from scratch. Explore the new features of Node.js 10, Express 4.0, and MongoDB. Integrate MongoDB in your Node.js application to store and secure your data. ➤ Read RESTful Web API Design with Node.js 10 - Third Edition. Learn Vue.js: The Collection For those of you looking for a comprehensive guide on Vue.js, we've made our collection available as a Kindle book on Amazon. It's a great companion to Jump Start Vue.js! Since its release in 2014, Vue.js has seen a meteoric rise to popularity and is is now considered one of the primary front-end frameworks, and not without good reason. Its component-based architecture was designed to be flexible and easy to adopt, making it just as easy to integrate into projects and use alongside non-Vue code as it is to build complex client-side applications. ➤ Buy Learn Vue.js: The Collection. 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 library for a spin. The post SitePoint Premium New Releases: SSGs, Interaction Design, Node & Vue appeared first on SitePoint.


A Deep Dive into Redux

Building stateful modern applications is complex. As state mutates, the app becomes unpredictable and hard to maintain. That's where Redux comes in. Redux is a lightweight library that tackles state. Think of it as a state machine. In this article, I’ll delve into Redux’s state container by building a payroll processing engine. The app will store pay stubs, along with all the extras — such as bonuses and stock options. I’ll keep the solution in plain JavaScript with TypeScript for type checking. Since Redux is super testable, I’ll also use Jest to verify the app. For the purposes of this tutorial, I’ll assume a moderate level of familiarity with JavaScript, Node, and npm. To begin, you can initialize this app with npm: npm init When asked about the test command, go ahead and put jest. This means npm t will fire up Jest and run all unit tests. The main file will be index.js to keep it nice and simple. Feel free to answer the rest of the npm init questions to your heart’s content. I’ll use TypeScript for type checking and nailing down the data model. This aids in conceptualizing what we’re trying to build. To get going with TypeScript: npm i typescript --save-dev I’ll keep dependencies that are part of the dev workflow in devDependencies. This makes it clear which dependencies are for developers and which goes to prod. With TypeScript ready, add a start script in the package.json: "start": "tsc && node .bin/index.js" Create an index.ts file under the src folder. This separates source files from the rest of the project. If you do an npm start, the solution will fail to execute. This is because you’ll need to configure TypeScript. Create a tsconfig.json file with the following configuration: { "compilerOptions": { "strict": true, "lib": ["esnext", "dom"], "outDir": ".bin", "sourceMap": true }, "files": [ "src/index" ] } I could have put this configuration in a tsc command-line argument. For example, tsc src/index.ts --strict .... But it’s much cleaner to go ahead and put all this in a separate file. Note the start script in package.json only needs a single tsc command. Here are sensible compiler options that will give us a good starting point, and what each option means: strict: enable all strict type checking options, i.e., --noImplicitAny, --strictNullChecks, etc. lib: list of library files included in the compilation outDir: redirect output to this directory sourceMap: generate source map file useful for debugging files: input files fed to the compiler Because I’ll be using Jest for unit testing, I'll go ahead and add it: npm i jest ts-jest @types/jest @types/node --save-dev The ts-jest dependency adds type checking to the testing framework. One gotcha is to add a jest configuration in package.json: "jest": { "preset": "ts-jest" } This makes it so the testing framework picks up TypeScript files and knows how to transpile them. One nice feature with this is you get type checking while running unit tests. To make sure this project is ready, create a __tests__ folder with an index.test.ts file in it. Then, do a sanity check. For example: it('is true', () => { expect(true).toBe(true); }); Doing npm start and npm t now runs without any errors. This tells us we’re now ready to start building the solution. But before we do, let’s add Redux to the project: npm i redux --save This dependency goes to prod. So, no need to include it with --save-dev. If you inspect your package.json, it goes in dependencies. Payroll Engine in Action The payroll engine will have the following: pay, reimbursement, bonus, and stock options. In Redux, you can’t directly update state. Instead, actions are dispatched to notify the store of any new changes. So, this leaves us with the following action types: const BASE_PAY = 'BASE_PAY'; const REIMBURSEMENT = 'REIMBURSEMENT'; const BONUS = 'BONUS'; const STOCK_OPTIONS = 'STOCK_OPTIONS'; const PAY_DAY = 'PAY_DAY'; The PAY_DAY action type is useful for dolling out a check on pay day and keeping track of pay history. These action types guide the rest of the design as we flesh out the payroll engine. They capture events in the state lifecycle — for example, setting a base pay amount. These action events can attach to anything, whether that be a click event or a data update. Redux action types are abstract to the point where it doesn’t matter where the dispatch comes from. The state container can run both on the client and/or server. TypeScript Using type theory, I’ll nail down the data model in terms of state data. For each payroll action, say an action type and an optional amount. The amount is optional, because PAY_DAY doesn’t need money to process a paycheck. I mean, it could charge customers but leave it out for now (maybe introducing it in version two). So, for example, put this in src/index.ts: interface PayrollAction { type: string; amount?: number; } For pay stub state, we need a property for base pay, bonus, and whatnot. We’ll use this state to maintain a pay history as well. This TypeScript interface ought to do it: interface PayStubState { basePay: number; reimbursement: number; bonus: number; stockOptions: number; totalPay: number; payHistory: Array<PayHistoryState>; } The PayStubState is a complex type, meaning it depends on another type contract. So, define the payHistory array: interface PayHistoryState { totalPay: number; totalCompensation: number; } With each property, note TypeScript specifies the type using a colon. For example, : number. This settles the type contract and adds predictability to the type checker. Having a type system with explicit type declarations enhances Redux. This is because the Redux state container is built for predictable behavior. This idea isn’t crazy or radical. Here’s a good explanation of it in Learning Redux, Chapter 1 (SitePoint Premium members only). As the app mutates, type checking adds an extra layer of predictability. Type theory also aids as the app scales because it’s easier to refactor large sections of code. Conceptualizing the engine with types now helps to create the following action functions: export const processBasePay = (amount: number): PayrollAction => ({type: BASE_PAY, amount}); export const processReimbursement = (amount: number): PayrollAction => ({type: REIMBURSEMENT, amount}); export const processBonus = (amount: number): PayrollAction => ({type: BONUS, amount}); export const processStockOptions = (amount: number): PayrollAction => ({type: STOCK_OPTIONS, amount}); export const processPayDay = (): PayrollAction => ({type: PAY_DAY}); What’s nice is that, if you attempt to do processBasePay('abc'), the type checker barks at you. Breaking a type contract adds unpredictability to the state container. I’m using a single action contract like PayrollAction to make the payroll processor more predictable. Note amount is set in the action object via an ES6 property shorthand. The more traditional approach is amount: amount, which is long-winded. An arrow function, like () => ({}), is one succinct way to write functions that return an object literal. Reducer as a Pure Function The reducer functions need a state and an action parameter. The state should have an initial state with a default value. So, can you imagine what our initial state might look like? I’m thinking it needs to start at zero with an empty pay history list. For example: const initialState: PayStubState = { basePay: 0, reimbursement: 0, bonus: 0, stockOptions: 0, totalPay: 0, payHistory: [] }; The type checker makes sure these are proper values that belong in this object. With the initial state in place, begin creating the reducer function: export const payrollEngineReducer = ( state: PayStubState = initialState, action: PayrollAction): PayStubState => { The Redux reducer has a pattern where all action types get handled by a switch statement. But before going through all switch cases, I’ll create a reusable local variable: let totalPay: number = 0; Note that it’s okay to mutate local variables if you don’t mutate global state. I use a let operator to communicate this variable is going to change in the future. Mutating global state, like the state or action parameter, causes the reducer to be impure. This functional paradigm is critical because reducer functions must remain pure. If you’re struggling with this paradigm, check out this explanation from JavaScript Novice to Ninja, Chapter 11 (SitePoint Premium members only). Start the reducer’s switch statement to handle the first use case: switch (action.type) { case BASE_PAY: const {amount: basePay = 0} = action; totalPay = computeTotalPay({...state, basePay}); return {...state, basePay, totalPay}; I’m using an ES6 rest operator to keep state properties the same. For example, ...state. You can override any properties after the rest operator in the new object. The basePay comes from destructuring, which is a lot like pattern matching in other languages. The computeTotalPay function is set as follows: const computeTotalPay = (payStub: PayStubState) => payStub.basePay + payStub.reimbursement + payStub.bonus - payStub.stockOptions; Note you deduct stockOptions because the money will go towards buying company stock. Say you want to process a reimbursement: case REIMBURSEMENT: const {amount: reimbursement = 0} = action; totalPay = computeTotalPay({...state, reimbursement}); return {...state, reimbursement, totalPay}; Since amount is optional, make sure it has a default value to reduce mishaps. This is where TypeScript shines, because the type checker picks up on this pitfall and barks at you. The type system knows certain facts so it can make sound assumptions. Say you want to process bonuses: case BONUS: const {amount: bonus = 0} = action; totalPay = computeTotalPay({...state, bonus}); return {...state, bonus, totalPay}; This pattern makes the reducer readable because all it does is maintain state. You grab the action’s amount, compute total pay, and create a new object literal. Processing stock options is not much different: case STOCK_OPTIONS: const {amount: stockOptions = 0} = action; totalPay = computeTotalPay({...state, stockOptions}); return {...state, stockOptions, totalPay}; For processing a paycheck on pay day, it’ll need to blot out bonus and reimbursement. These two properties don’t remain in state per paycheck. And, add an entry to pay history. Base pay and stock options can stay in state because they don’t change as often per paycheck. With this in mind, this is how PAY_DAY goes: case PAY_DAY: const {payHistory} = state; totalPay = state.totalPay; const lastPayHistory = payHistory.slice(-1).pop(); const lastTotalCompensation = (lastPayHistory && lastPayHistory.totalCompensation) || 0; const totalCompensation = totalPay + lastTotalCompensation; const newTotalPay = computeTotalPay({...state, reimbursement: 0, bonus: 0}); const newPayHistory = [...payHistory, {totalPay, totalCompensation}]; return {...state, reimbursement: 0, bonus: 0, totalPay: newTotalPay, payHistory: newPayHistory}; In an array like newPayHistory, use a spread operator, which is the reverse of rest. Unlike rest, which collects properties in an object, this spreads items out. So, for example, [...payHistory]. Even though both these operators look similar, they aren’t the same. Look closely, because this might come up in an interview question. Using pop() on payHistory doesn’t mutate state. Why? Because slice() returns a brand new array. Arrays in JavaScript are copied by reference. Assigning an array to a new variable doesn’t change the underlying object. So, one must be careful when dealing with these types of objects. Because there’s a chance lastPayHistory is undefined, I use poor man’s null coalescing to initialize it to zero. Note the (o && o.property) || 0 pattern to coalesce. Maybe a future version of JavaScript or even TypeScript will have a more elegant way of doing this. Every Redux reducer must define a default branch. To make sure state doesn’t become undefined: default: return state; The post A Deep Dive into Redux appeared first on SitePoint.


Code Challenge #2: The Test of Characters

I’ve been a big fan Kushagra Gour since the early days of Webmaker – his CodePen-like code playground running as a Chrome Extension. I use it most days. More recently he teamed up Kushagra Agarwal to work on a new project ‘CSSBattle.dev‘ – a cool and original blend of CSS coding and golf. Be warned […] The post Code Challenge #2: The Test of Characters appeared first on SitePoint.


So, Do we Have a Winner for Code Challenge #1?

It’s been a week since we launched our quick Code Challenge #1, which means it’s time to announce a winner! It was tricky. While the quantity of entries wasn’t high, there’s no questioning the quality of our winning entries. But first, let’s run through a few different approaches to the challenge we supplied. My turn […] The post So, Do we Have a Winner for Code Challenge #1? appeared first on SitePoint.


10 Top Chrome Extensions for Your Web Development Workflow

As web developers we work in a very fast paced industry and staying on top of things can sometimes be a challenge. That's why I believe we should take full advantage of whatever tools we have at our disposal to help keep our heads above water. Today I'm going to present ten Chrome extensions that are geared to optimizing your web development workflow, hopefully making you that little bit more productive. What are Chrome Extensions? As can be read on Chrome's developer portal, extensions are small software programs that can customize your browsing experience. This can be anything from a spelling and grammar checker that checks your writing as you type, to a password manager that saves your login details for your favorite sites. There are literally thousands of extensions available for Chrome, all of which can be downloaded for free from the Chrome Web Store. You can check which extensions you currently have installed by visiting the following link in your browser: chrome://extensions/. Why Chrome? This article focuses on the Google Chrome browser due to its huge market share (currently 65% and rising). There are also many Chrome-based browsers which support extensions. These include Brave, Vivaldi and, coming soon, Microsoft Edge. However, we should remember that Chrome isn't the only show in town and that many of the extensions mentioned here have a Firefox and/or Opera equivalent. Finally, before we dive into the extensions, take a minute to remember that Chrome is proprietary software published by Google. As we all know, there are privacy concerns associated with using Google products, so maybe head over to GitHub and check out the ungoogled-chromium project instead. As the name suggests, this is Google Chromium, sans integration with Google. 1. Web Developer We'll start off with the Swiss Army knife of extensions. With over 1 million users and a 4.5 star rating on the Chrome Web Store, Web Developer is something of a must have. It adds a toolbar button to Chrome which, when clicked, displays a plethora of tools that can be used on any web page. These are grouped by category (CSS, forms, images etc) and allow you to do such things as disable JavaScript, outline images with missing alt attributes, resize the browser window, validate a page's HTML, view a page's meta tag information and much more. You can download it here. 2. Your Framework's Developer Tools If you're developing an app with a JavaScript framework and you're not using that framework's developer tools, then you're probably doing it wrong. Let me explain using Vue as an example. If you have a Vue app which you need to debug, or you just want to see what's going on under the hood, then what do you do? Inspecting the page's source will show you the HTML that Vue is rendering, but there is much more to a Vue app than that. What about a component's props, data or computed properties? Or your app's state or routing? How do you inspect any of those? The good news is that the Vue.js dev tools have you covered. Simply install the extension and open it up on a page running a development build of Vue to see exactly what is happening in your app. Here are links to download the dev tools for the big three frameworks. Vue React Ember 3. Daily 2.0 - Source for Busy Developer As we work in a fast paced industry, keeping up with news and goings on can sometimes be a challenge. Enter Daily 2.0, an extension that gathers the latest web development and tech posts from around the internet and presents them in an attractive masonry-style lay out on your new tab page. The extension is easy to use. When you install it you are asked to pick from a bunch of categories that interest you and Daily 2.0 does the rest. Hovering over the sidebar on the new tab page allows you to filter your feed based on tags and sources. You can get it here. 4. Toggl Button: Productivity & Time Tracker If you're a busy freelancer, if you work remotely, or if you just need to track the time you're spending on a project, then Toggl is for you. This extension requires you to create an account before you can use it. Once you're logged in it enables quick and easy real time productivity tracking with all the data stored in your Toggl account. It comes with a built-in Pomodoro timer, as well as integrations for a whole host of internet services (such as GitHub, Trello and Slack). One of my favorite features is that it will pop up a notification when you've been idle and the timer was running, allowing you to discard the time. Toggl can be downloaded here. 5. Lighthouse Lighthouse is an open-source, automated tool for improving the performance and quality of your web pages. You can either install it via the Chrome Web Store or, as of Chrome version 60, you can run it directly from the Audits tab of the browser's DevTools (press F12 and select Audits). Once you have opened Lighthouse, click Generate report and optionally select which audit categories to include. Lighthouse will run the selected audits against the page, and generate a report on how well the page did. From there, you can use the failing audits as indicators of how to improve the page. Each audit also includes links to further reading and potential fixes. Lighthouse is produced by Google, and presumably uses the same ranking factors as their search engine. This means it can offer you some of the best advice out there on how to optimize your site. You can grab it here. 6. OneTab The post 10 Top Chrome Extensions for Your Web Development Workflow appeared first on SitePoint.


How Analytics Helped Solve a UX Issue

UX and analytics make a great team. Your website analytics can give you insights enabling you to learn about your users, track their journeys, and find potential problem areas. You can use the quantitative data to inform your qualitative UX approach. Remember, your analytics tell you what’s happening on your website, while UX techniques such as usability testing will help uncover why things are happening. There are various ways that Google Analytics can be used to uncover how your users are navigating your website. Within the Pages report you can drill down to see how users are navigating to, and from, a selected page in your website. But the User Flow and Behavior Flow reports give more information on multi-step journeys from your most popular landing pages onwards. These reports can be hard to analyze, particularly for large websites, due to the fact that there are unlikely to be a series of clear pathways through your website. You’ll find that there are huge numbers of paths that different users can take, which makes finding insights from these reports quite challenging. However, they can be useful for getting a good top-level overview and showing the most dominant pathways through a site. While they suffer from grouping multiple pages, you can often get a good idea of the most common journeys taken by users. One example of how I’ve used these reports in the past to inform my UX work has been looking out for pogo sticking. Pogo Sticking Pogo sticking describes where users bounce between two pages on a website instead of progressing their journey through the site. It can be a sign of confusion on the users’ part and is unlikely to help you convert those users. The Nielson/Norman group wrote this guide to pogo sticking, which explains it in more detail. It covers some possible reasons behind pogo sticking behavior, and also gives some potential solutions to these problems. The post How Analytics Helped Solve a UX Issue appeared first on SitePoint.


SitePoint Premium New Releases: Design, Git, Android, Swift + 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. Exploring Git Workflows Most of us use version control systems on a daily basis. But even though we may use identical systems, we use them in different ways. In this tutorial, Claudio describes GitFlow, the current workflow used by his team. Read Exploring Git Workflows. Beginning Android Programming with Android Studio This hands-on introduction to creating Android apps shows how to install and get started with Android Studio 2, display notifications, create rich user interfaces, use activities and intents, master views and menus, manage data, work with SMS, and package and publish apps to the Android market. Read Beginning Android Programming with Android Studio. A Beginner’s Guide to Deployment with Continuous Integration This guide tackles an important technique in the processing of automating the deployment process—continuous integration (CI). CI achieves efficiency by removing unnecessary bottlenecks in the deployment process, thereby making the transition from a commit to production smooth and consistent. Read A Beginner’s Guide to Deployment with Continuous Integration. Design for Hackers This book explores principles of beautiful design, covering color theory, medium and form, classical principles and techniques, culture and context, the importance, purpose and constraints of design, fonts, scale and proportion, and even ancient graffiti, Monet, the iPhone, and much more. Read Design for Hackers. Swift 4 Protocol-Oriented Programming - Third Edition Build fast and powerful applications by harnessing the power of protocol-oriented programming in Swift 4. Learn from real-world cases, creating a flexible codebase with protocols and protocol extensions, leveraging the power of generics to create very flexible frameworks. Read Swift 4 Protocol-Oriented Programming - Third Edition. 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 library for a spin. The post SitePoint Premium New Releases: Design, Git, Android, Swift + More appeared first on SitePoint.


A Deep Dive into User Research Methods

User research plays a crucial role in shaping any successful product or service. It keeps the user at the heart of the experience by tailoring it to their needs, and in turn provides real advantage over competitors. But with a growing arsenal of different research methods out there, it can be a challenge to know which is best to use, and when. This guide offers an overview of the fundamentals for each of the most commonly used methods, providing direction on when to use them — and more importantly, why. We’ll cover: the origins of user research discovery and exploratory research quant and qual, and the difference between them core methodologies: user interviews ethnography and field studies surveys and questionnaires analytics and heatmaps card sorts and tree tests usability studies further reading and resources key takeaways The Origins of User Research Product designers and engineers have incorporated user feedback into their process for centuries. However, it wasn’t until 1993 that the term “user experience” (UX) was coined by Don Norman during his time at Apple. As the discipline of UX evolved and matured, practitioners began to use investigative research techniques from other fields, such as science and market research. This enabled decisions to be informed by the end user, rather than the design teams’ assumptions, laying the groundwork for UX research as we know it today. That’s a quick rundown of the origins. Now let’s dive into some research frameworks. Discovery and Evaluative Research User-centered design means working with your users all throughout the project — Don Norman Broadly speaking, user research is used to either discover what people want and need or evaluate if ideas are effective. The methods to achieve these two distinct outcomes can be loosely divided into two groups. Strategize: Discovery Research Methods that help to answer unknowns at the beginning of a project can be referred to as Discovery Research. These methods range from reviewing existing reports, data and analytics to conducting interviews, surveys and ethnographic studies. These methods ensure that you have a solid understanding of who your user is, what they need and the problems they face in order to begin developing a solution. Execute and Assess: Evaluative Research Once a clearer picture of the end user and their environment has been established, it’s time to explore possible solutions and test their validity. Usability studies are the most common method employed here. Evaluative research provides you with the knowledge you need to stay focussed on the user and their specific requirements. Examples Discovery Research Methods Evaluative Research Methods field study diary study one-to-one interview focus group behavioral analytics review open card sort email survey contextual inquiry remote usability testing closed card sort tree test benchmarking analytics review heatmaps popup poll usability benchmark testing impression testing Quant and Qual, and the Difference Between Them Although every design problem is different, it’s generally agreed that a combination of both qualitative and quantitative research insights will provide a balanced foundation with which to form a more successful design solution. But what do these pronunciation-averse words mean? Quantitative (statistical) research techniques involve gathering large quantities of user data to understand what is currently happening. This answers important questions such as “where do people drop off during a payment process”, or “which products were most popular with certain user groups” and “what content is most/least engaging”. Quantitative research methods are often used to strategize the right direction at the start of a project and assess the performance at the end using numbers or metrics. Common goals include: comparing two or more products or designs getting benchmarks to compare the future design against calculating expected cost savings from some design changes Quantitative data analysis can offer useful insights such as abandonment points on a form. This can lead to further qualitative studies to understand why. Qualitative (observational) research techniques involves directly observing small user groups to understand attitudes, behaviors and motivations. This is where we begin to understand why something is happening and how to solve a problem. You can optimize everything and still fail. That’s where qualitative approaches come in. By asking “why”, we can see the opportunity for something better beyond the bounds of the current best. ― Erika Hall Qualitative research methods are also used to strategize the right direction at the start of a project, and to inform design decisions throughout the ideation process. Common goals include: to uncover trends in thoughts and opinions understand a problem more deeply to develop a hypothesis for a quantitative research study Christian Rohrer authored a popular framework for understanding user research methods, illustrating where 20 popular methods appear along three dimensions, including quantitative and qualitative. Source. Core Methodologies So that’s enough of the background behind the methods. Let’s dive into the methods themselves. It’s worth noting that, since every project is different, there’s no quick way of strictly stating which method is best for what. However, pros and cons have been listed for each. 1. User interviews Qualitative | Discover/Evaluate Interviews allow you to ask questions to help see things from the participants’ perspective. They are usually recorded and later analyzed to find out what the beliefs, attitudes and drivers of users are, alongside uncovering new considerations to aid with ideation. Stories are where the richest insights lie. Your objective is to get to this point in every interview. — Steve Portigal Interview length, style and structure can vary depending on what you’re trying to achieve, and the access to and availability of participants. The following are some different types of interviews. One-to-one interviews are often conducted in a lab or coffee shop, but can be undertaken almost anywhere with a little preparation. In-person interviews are preferable to remote (via phone or video) as they offer additional insights through body language. Sessions are conducted with questions that loosely follow a discussion guide. This allows you to uncover new learnings around an objective and not get sidetracked. Focus groups are used to gain a consensus from a group of 3–10 representatives of a target audience when you’re short on time or availabile participants. Focus groups take the form of discussions and exercises and are a good way of assessing what people want from a product or service and their opinions on things. They’re not recommended for evaluating interface usability, due to their lack of focus and the potential for groupthink bias. Contextual inquiry interviews are the holy grail of interview methods. They’re conducted within the participants’ everyday environment whilst they go about their daily activities. A researcher can observe a participant and discuss what they did, and why, whilst the activities take place. Unlike other interviews, the researcher usually summarizes the findings back to the participant at the end, offering them a chance to give final corrections and clarifications. This method is used to generate highly relevant and reliable insights from real situations, but it can be very time consuming. For more on user interviews, there’s some great resources on the Interaction Design Foundation website. 2. Field Studies Qualitative | Discover Field studies involve observing people as they interact with a product, service, or each other, in their natural working or living environment (rather than in a lab) to better understand user behavior and motivations in context. These studies are usually conducted over longer periods of time than most other methods, recording extensive field notes for later analysis. Ethnographic research involves researchers actively participating within a group setting, becoming the subject themselves. This method is particularly useful when studying a target audience that is culturally or socially different from your own, and it can uncover lots of unknowns and important considerations. Direct observation involves passively observing from a distance (like a curious fly on a wall), allowing researchers to uncover problems and workarounds in user journeys and flows (such as retail store layouts), and also allowing for future improvements. User logs involve diary studies and video journals, and are sometimes referred to as the “poor man’s field study”. They allow the user to generate the data for you by recording their experiences with the focus of the study at a specific time each day over a period of time. The real-time insights provided can be useful for understanding long-term behaviors such as habits, workflows, attitudes, motivations, or changes in behavior. The post A Deep Dive into User Research Methods appeared first on SitePoint.


How to Replace Redux with React Hooks and the Context API

The most popular way for handling shared application state in React is using a framework such as Redux. Quite recently, the React team introduced several new features which include React Hooks and the Context API. These two features effectively eliminated a lot of challenges that developers of large React projects have been facing. One of the biggest problems was 'prop drilling' which was common with nested components. The solution was to use a state management library like Redux. This unfortunately came with the expense of writing boilerplate code — but now, it's possible to replace Redux with React Hooks and the Context API. In this article, you are going to learn a new way of handling state in your React projects without writing excessive code or installing a bunch of libraries as is the case with Redux. React hooks allows you to use local state inside of function components, while the Context API allows you to share state with other components. Prerequisites In order to follow along with this tutorial, you will need to have a good foundation in the following topics: Getting Started with React React Hooks Foundation in Redux The technique you will learn here is based on patterns that were introduced in Redux. This means you need to have a firm understanding of reducers and actions before proceeding. I am currently using Visual Studio Code, which seems to be the most popular code editor right now (especially for JavaScript developers). If you are on Windows, I would recommend you install Git Bash. Use the Git Bash terminal to perform all commands provided in this tutorial. Cmder is also a good terminal capable of executing most Linux commands on Windows. You can access the complete project used in this tutorial from this GitHub Repository. The post How to Replace Redux with React Hooks and the Context API appeared first on SitePoint.


UI Code Challenge #1 – Heartbeats

Do you ever find that the UI screens that we see in blockbuster movies, television, and games are so much more fun than the UIs we might build at work? Here's your chance to code something fun and maybe even win an Amazon Gift Card. The post UI Code Challenge #1 – Heartbeats appeared first on SitePoint.


Content as UX: Building a More Human Web

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. How are you enjoying this article so far? Whatever your feelings, I’ll bet you’ll agree that content is a vital part of the user experience. Wait. Did I say “a vital part”? I meant “the critical part”. After all, every user journey, whatever its goal, ultimately involves a user getting to content, or adding their own. That content may be text, like this article, or it may be imagery, video, audio — you name it. But whatever it is, it’s the point of the user’s interaction with every site or product. Yet traditionally (and all too often still) when we design websites or make products, we design visually, and the content spaces are left blank. If you’re doing things as most do, you’re probably going to show the wireframes or mockups to someone internal — maybe even your founder — and ask them to fill the spaces. Ugh. At least, that’s what your colleague is probably thinking at this point. Now they have the burden and responsibility of filling the literal and metaphorical blank page — but a blank page that already has a goal or direction they’ve had no part in choosing. Here I’m going to suggest an alternative way to consider content, where content is UX. 1. How Can Content Be UX? I said above that content is the critical part of the UX. Let’s build on that now. Content is user experience. Look at a site like YouTube. The landing page is a list of content. Even better, that content is presented based on your (or my) past usage patterns. The data associated with that content — the image, title, name of the account that uploaded the media, total views and upload date — is also content. When you access a video, the comments beneath it are content. It’s all content. Content is the user experience. It’s what we’re here to use. Okay, you say, but it’s YouTube. My product isn’t content. Fine, let’s consider the example of a new computer. I just had to replace mine after six years of trusty service. I got a MacBook Air, and it came in a lovely box. Nice user experience. Other than the actual computer, there’s not much content here, right? Well, no. But then I open the box, plug the thing in, and notice these little leaflets tucked away. I’ve included the matchbox for a size comparison. I wear glasses, but I felt like I needed a magnifying glass to read the leaflet titled MacBook Air Info. In fact, I only read the first sentence (which hurt my eyes): Review the Macbook Air Essentials guide before using MacBook Air. “Right you are, Apple,” I thought. But what’s this? The only other leaflet in the box is a MacBook Air Quick Start Guide. Is … is that what they meant? I hope so, because it has slightly bigger text, and it was the only other thing I glanced through before I turned on my thrilling new purchase. Question: how am I ever going to start creating glorious content on that device, or access the glorious content accessible on the Web, if I can’t read the instruction content to get said device going? If I don’t need the content to get it work, then why include these crazy-tiny, unreadable leaflets with the product in the first place? This experience doesn’t exactly fill me with confidence, nor the idea that Apple cares about actual people. Sure, the packaging is nice. But right now it feels like the business is in love with its own products more than its users. Bottom line: content is user experience. Even in the Real World™. The post Content as UX: Building a More Human Web appeared first on SitePoint.


SitePoint Premium New Releases: Docker, Phoenix, VS Code + 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. Phoenix Web Development Learn functional programming through building a high-performance functional prototype of a web app from scratch using Elixir and Phoenix. Understand the Elixir Concurrency and parallelization model to build blazingly fast apps. Test, debug and deploy your web apps using the Phoenix framework. Read Phoenix Web Development. Debugging with Visual Studio Code: An Introduction Learn to use Visual Studio Code's built-in debugging features which permit easier debugging and variable monitoring. Discover how you can improve your debugging experience! Read Debugging with Visual Studio Code: An Introduction. Docker Cookbook Second Edition Docker is an open source platform for building, shipping, managing, and securing containers. This book includes practical exmaples showing you how to manage containers efficiently; how to integrate with orchestration tools such as Kubernetes; and best practices on improving the efficiency and security of containers. Read Docker Cookbook Second Edition. Beginning ASP.NET 4.5.1 in C# and VB This book covers how to get started with ASP.NET 4.5.1; how to overcome common HTML and CSS formatting problems; techniques for managing server controls; creating consistent page layouts; the ASP.NET state engine; modifying SQL data; and also jQuery, LINQ, the Entity Framework, and security. Read Beginning ASP.NET 4.5.1 in C# and VB. A Pocket Guide to HTML Email Creating HTML emails is often thought of as an unpleasant and neglected part of web design, but email is hugely important for reaching out to your users, customers and clients. In this book, Andy shows you how to design and build responsive email your customers and clients will love to receive. Read A Pocket Guide to HTML Email. 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 library for a spin. The post SitePoint Premium New Releases: Docker, Phoenix, VS Code + More appeared first on SitePoint.


Introduction to Vue.js and the Quasar Framework

In recent years, we’ve seen a proliferation of JavaScript tools and frameworks, such as Angular and React. I remember when I bought a book about Grunt.js: it was already being dropped by developers, who had started using other tools like Gulp, “the streaming build system”. But anyone who jumped on that train was likely to switch again really fast, because webpack came along and replaced them all. But among JavaScript frameworks, one has seen particularly rapid growth in recent years: Vue.js. It’s been so popular that its rate of growth has become explosive compared to others in this space. Vue has become one of the primary contenders due its soft learning curve. It lends itself nicely to gradual implementation. It has a modular, component-based architecture. And it has wide usage and a developed ecosystem of tools. If you’re interested in getting started with Vue, you can check out our book Jump Start Vue.js to start getting on your way to using Vue in your projects. Vue Tools, Terminology and Landscape As with most technologies one ventures to master, getting to grips with Vue includes getting to know the terms and concepts, and getting comfortable with its ecosystem of tools and building blocks. Vue Router is an indispensable part of all Vue single-page applications. It provides navigation control, nested routing, route-view mapping, and many other features. Vuex is a “state management pattern + library” for Vue apps. It’s like a centralized data store helping us to manage state in our applications, across all components. Handling stage across multiple parts of front-end applications can quickly get out of hand, and thus the need for a comprehensive solution. We talk more about Vuex in our Vuex Beginners Guide. Vue devtools can make life easier for developers. It helps you keep track of the components, state, and events in our applications. You can find more about this tool in Chapter 2 of our book dedicated to Vue tools. Vue Cli provides a command-line toolset for building Vue applications — prototyping, fast scaffolding of JavaScript applications with included CSS pre-processors, ESLint, Babel, Typescript support, PWA support, and so on. Vue CLI — especially in its latest incarnation — is a game changer, and presents a little ecosystem of its own. The Vue CLI 3 plugin for building Electron applications is one very good example. We also devoted a whole book to it, the Beginner’s Guide to Vue CLI, so you can dive right in. Vue Component System is another one of Vue’s strengths. It enables us to modularize our applications, to encapsulate pieces of markup, logic and styling and reuse them. Vue Cli Plugin Component, by David Desmaisons, helps with development of components to be published on npm. If you’re looking for a deep dive into these and other Vue.js tools, I recommend you take a look through Vue.js: Tools & Skills. Awesome Vue is also an excellent resource. It’s an in-depth, categorized, up-to-date collection/repo of all the pieces of the Vue ecosystem and Vue.js resources. Quasar, the Vue framework we’re covering here, also has Awesome Quasar, an excellent repo page with many useful resources. Quasar Vue is a JavaScript framework for building user interfaces. On its own, however, it doesn’t provide actual UI elements, or components, or consistent designs we can use. That’s why, on top of Vue, many UI frameworks have been built, to provide users with reusable, styled components. We can think of it like different takes on Twitter’s Bootstrap — only for Vue. If you’re interested in finding out more, I recommend taking a look at “Five Vue UI Libraries for Your Next Project”, which is Chapter 3 of Vue.js: Tools & Skills. One serious contender in this space, which we didn’t cover, is Vuetify, a material design component framework with quite a big following. Another one is Quasar. Quasar is a high performance, Material Design 2, full front-end stack for Vue.js. It’s an MIT-licensed, simple-to-use but powerful UI kit that supplements Vue.js to provide a full-featured toolset for building responsive front-end apps without having to delve too deep into the scaffolding and configuration. As we can see in the Quasar docs, it comes with a lot of UI components, and layout elements and helpers. It gives us three ways to bootstrap our app: UMD / Standalone makes it possible to start small, by including scripts and styles we need from a CDN. This method doesn’t rely on VUE CLI or the building of assets. Quasar CLI claims to be “the pride of the Quasar framework”, and is the recommended way of building Quasar applications. It can be used to build: SPAs (single-page apps/websites) SSRs (server-side rendered apps/websites) PWAs (progressive web apps) mobile apps (through Cordova) Electron apps Vue CLI 3 plugin We’ll follow Quasar team’s recommendation and use Quasar CLI. Bootstrapping a Quasar App with Quasar CLI Before we install Quasar CLI, we need to make sure we have the right versions of node (>= 8 at the time of writing) and npm (>= 5). If not, we need to either install or update it. Then we can install Quasar CLI: sudo npm install -g @quasar/cli Now we can use it to bootstrap our projects. Quasar has a thorough documentation on Quasar CLI. We’ll skim through it and discuss most relevant parts. The command we use is quasar + subcommand. Just quasar will list the commands for us, and quasar <command> --help will get us the help for the given subcommand. We use quasar create to scaffold a quasar project. We’re then presented with a list of choices about the project we want to bootstrap. After the project is scaffolded, we can cd into the directory and start a development server with quasar dev. The project is built and the browser will open the provisional index page on localhost. Note: for production, once our project is done, we’d be using quasar build to compile our resources. The dev server provides us with Hot Reload, which preserves the state in the browser through reloads. Hot Reload is much more than just refreshing your browser when the code changes. It skips the refresh and updates your code on the fly, while maintaining your app’s state (like your Vue’s model data). As we write code and save our files/Vue components, along with a page reload in the browser, the terminal shell in which we started the dev server will output many errors in the code. This section in Vue.js: Tools & Skills gives a pretty good explanation of why. Once we’ve bootstrapped our project, we get this directory structure (with the exclusion of node_modules): The post Introduction to Vue.js and the Quasar Framework appeared first on SitePoint.


How to Build a Chrome Extension with Vue

Browser extensions are small programs that can modify and enhance the functionality of a web browser. They can be used for a variety of tasks, such as blocking ads, managing passwords, organizing tabs, altering the look and behavior of web pages, and much more. The good news is that browser extensions aren’t difficult to write. They can be created using the web technologies you’re already familiar with — HTML, CSS and JavaScript — just like a regular web page. However, unlike regular web pages, extensions have access to a number of browser-specific APIs, and this is where the fun begins. In this tutorial, I’m going to show you how to build a simple extension for Chrome, which alters the behavior of the new tab page. For the JavaScript part of the extension, I’ll be using the Vue.js framework, as it will allow us to get up and running quickly and is a lot of fun to work with. The code for this tutorial can be found on GitHub. The Basics of a Chrome Extension The core part of any Chrome extension is a manifest file and a background script. The manifest file is in a JSON format and provides important information about an extension, such as its version, resources, or the permissions it requires. A background script allows the extension to react to specific browser events, such as the creation of a new tab. To demonstrate these concepts, let’s start by writing a “Hello, World!” Chrome extension. Make a new folder called hello-world-chrome and two files: manifest.json and background.js: mkdir hello-world-chrome cd hello-world-chrome touch manifest.json background.js Open up manifest.json and add the following code: { "name": "Hello World Extension", "version": "0.0.1", "manifest_version": 2, "background": { "scripts": ["background.js"], "persistent": false } } The name, version and manifest_version are all required fields. The name and version fields can be whatever you want; the manifest version should be set to 2 (as of Chrome 18). The background key allows us to register a background script, listed in an array after the scripts key. The persistent key should be set to false unless the extension uses chrome.webRequest API to block or modify network requests. Now let’s add the following code to background.js to make the browser say hello when the extension is installed: chrome.runtime.onInstalled.addListener(() => { alert('Hello, World!'); }); Finally, let’s install the extension. Open Chrome and enter chrome://extensions/ in the address bar. You should see a page displaying the extensions you’ve installed. As we want to install our extension from a file (and not the Chrome Web Store) we need to activate Developer mode using the toggle in the top right-hand corner of the page. This should add an extra menu bar with the option Load unpacked. Click this button and select the hello-world-chrome folder you created previously. Click Open and you should see the extension installed and a “Hello, World!” popup appear. Congratulations! You just made a Chrome extension. Overriding Chrome’s New Tab Page The next step will to have our extension greet us when we open up a new tab. We can do this by making use of the Override Pages API. Note: before you progress, please make sure to disable any other extensions which override Chrome’s new tab page. Only one extension at a time may alter this behavior. We’ll start off by creating a page to display instead of the new tab page. Let’s call it tab.html. This should reside in the same folder as your manifest file and background script: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My New Tab Page!</title> </head> <body> <h1>My New Tab Page!</h1> <p>You can put any content here you like</p> </body> </html> Next we need to tell the extension about this page. We can do so by specifying a chrome_url_overrides key in our manifest file, like so: "chrome_url_overrides": { "newtab": "tab.html" } Finally, you need to reload the extension for the changes to take effect. You can do this by clicking the reload icon for the Hello World extension on Chrome’s extensions page. Now, when you open a new tab, you should be greeted by your custom message. Adding Vue to the Extension Now we have a very basic implementation of our extension up and running, the time has come to think about what the rest of the desired functionality will look like. When a user opens a new tab, I would like the extension to: Fetch a joke from the wonderful icanhazdadjoke.com. Display that joke in a nicely formatted manner to the user. Display a button for the user to favorite the joke. This will save the joke to chrome.storage. Display a button for the user to list favorited jokes. You could, of course, do all of this with plain JavaScript, or a library like jQuery — and if that’s your thing, feel free! For the purposes of this tutorial, however, I’m going to implement this functionality using Vue and the awesome vue-web-extension boilerplate. Using Vue allows me to write better, more organized code faster. And as we’ll see, the boilerplate provides several scripts that take the pain out of some of the common tasks when building a Chrome extension (such as having to reload the extension whenever you make changes). vue-web-extension-boilerplate This section assumes that you have Node and npm installed on your computer. If this isn’t the case, you can either head to the project’s home page and grab the relevant binaries for your system, or you can use a version manager. I would recommend using a version manager. We’ll also need Vue CLI installed and the @vue/cli-init package: npm install -g @vue/cli npm install -g @vue/cli-init With that done, let’s grab a copy of the boilerplate: vue init kocal/vue-web-extension new-tab-page This will open a wizard which asks you a bunch of questions. To keep this tutorial focused, I answered as follows: ? Project name new-tab-page ? Project description A Vue.js web extension ? Author James Hibbard <jim@example.com> ? License MIT ? Use Mozilla's web-extension polyfill? No ? Provide an options page? No ? Install vue-router? No ? Install vuex? No ? Install axios? Yes ? Install ESLint? No ? Install Prettier? No ? Automatically install dependencies? npm You can adapt your answers to suit your preferences, but the main thing to be certain of is that you choose to install axios. We’ll be using this to fetch the jokes. Next, change into the project directory and install the dependencies: cd new-tab-page npm install And then we can build our new extension using one of the scripts the boilerplate provides: npm run watch:dev This will build the extension into a dist folder in the project root for development and watch for changes. To add the extension to Chrome, go through the same process as outlined above, making sure to select the dist folder as the extension directory. If all goes according to plan, you should see a “Hello world!” message when the extension initializes. Project Setup Let’s take a minute to look around our new project and see what the boilerplate has given us. The current folder structure should look like this: . ├── dist │ └── <the built extension> ├── node_modules │ └── <one or two files and folders> ├── package.json ├── package-lock.json ├── scripts │ ├── build-zip.js │ └── remove-evals.js ├── src │ ├── background.js │ ├── icons │ │ ├── icon_128.png │ │ ├── icon_48.png │ │ └── icon.xcf │ ├── manifest.json │ └── popup │ ├── App.vue │ ├── popup.html │ └── popup.js └── webpack.config.js As you can see, from the config file in the project root, the boilerplate is using webpack under the hood. This is awesome, as this gives us Hot Module Reloading for our background script. The src folder contains all of the files we’ll be using for the extension. The manifest file and background.js should be familiar, but also notice a popup folder containing a Vue component. When the boilerplate builds the extension into the dist folder, it will pipe any .vue files through the vue-loader and output a JavaScript bundle which the browser can understand. Also in the src folder is an icons folder. If you look in Chrome’s toolbar, you should see a new icon for our extension (also known as the browser action). This is being pulled from this folder. If you click it, you should see a popup open which displays “Hello world!” This is created by popup/App.vue. Finally, note a scripts folder containing two scripts — one to remove eval usages to comply with the Content Security Policy of Chrome Web Store and one to package your extension into a .zip file, which is necessary when uploading it to the Chrome Web Store. There are also various scripts declared in the package.json file. We’ll be using npm run watch:dev for developing the extension and later on npm run build-zip to generate a ZIP file to upload to the Chrome Web Store. The post How to Build a Chrome Extension with Vue appeared first on SitePoint.


Build a Desktop Application with Electron and Angular

In this tutorial we’ll build a cross-platform desktop application with Electron and web technologies such as TypeScript and Angular. Electron.js is a popular platform for building cross-platform desktop apps for Windows, Linux and macOS with JavaScript, HTML, and CSS. It’s created and maintained by GitHub and it’s available under the MIT permissive license. It was […] The post Build a Desktop Application with Electron and Angular appeared first on SitePoint.


Non-relational Databases and Supporting Mixed Workloads

This article was created in partnership with MongoDB. Thank you for supporting the partners who make SitePoint possible. Suppose that you’re building an e-commerce platform and as part of the exercise, you need to come up with a new data architecture for inventory management. You need to support fast, transactional workloads to actually keep track of inventory in near real-time. The business would also like to be able to answer questions such as "based on historical data, when should we restock on widgets and gizmos?" and “who are the people that are buying widgets and generally, where are they located?” Your data architecture needs to support mixed workloads. Where would you start? The post Non-relational Databases and Supporting Mixed Workloads appeared first on SitePoint.


SitePoint Premium New Releases: Webpack, TensorFlow, Swift & Parcel

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. A Beginner’s Guide to Webpack When using JavaScript module bundler webpack for the first time, it can be difficult to […] The post SitePoint Premium New Releases: Webpack, TensorFlow, Swift & Parcel appeared first on SitePoint.


A Beginner’s Guide to Webpack

Nowadays, we’re forced to use many accessory tools to facilitate, speed up and optimize our web development workflow. Often though, such tools add an extra layer of complexity into the stack. As a result, we need to utilize additional time and effort to learn, understand and use these tools correctly. The same is true for webpack. When using webpack for the first time, it can be difficult to understand how it works and how it should be used. Although it has good documentation, it can be daunting for novices, and it has a steep learning curve. However, webpack is worth learning and can save considerable time and effort in the long run. In this tutorial, I’ll introduce all the core concepts to help you get started. Note: in this tutorial I’ve used webpack 4.30. What Is Webpack? As its core, webpack is a static module bundler. In a particular project, webpack treats all files and assets as modules. Under the hood, it relies on a dependency graph. A dependency graph describes how modules relate to each other using the references (require and import statements) between files. In this way, webpack statically traverses all modules to build the graph, and uses it to generate a single bundle (or several bundles) — a JavaScript file containing the code from all modules combined in the correct order. “Statically” means that, when webpack builds its dependency graph, it doesn’t execute the source code but stitches modules and their dependencies together into a bundle. This can then be included in your HTML files. Now, to expand the above cursory overview, let’s explore the main concepts webpack uses. Webpack Main Concepts Webpack has some main concepts which we need to understand clearly before digging in its practical implementation. Let’s examine them one by one: Entry. The entry point is the module, which webpack uses to start building its internal dependency graph. From there, it determines which other modules and libraries that entry point depends on (directly and indirectly) and includes them in the graph until no dependency is left. By default, the entry property is set to ./src/index.js, but we can specify a different module (or even multiple modules) in the webpack configuration file. Output. The output property instructs webpack where to emit the bundle(s) and what name to use for that file(s). The default value for this property is ./dist/main.js for the main bundle and ./dist for other generated files — such as images, for example. Of course, we can specify different values in the configuration depending on our needs. Loaders. By default, webpack only understands JavaScript and JSON files. To process other types of files and convert them into valid modules, webpack uses loaders. Loaders transform the source code of non-JavaScript modules, allowing us to preprocess those files before they’re added to the dependency graph. For example, a loader can transform files from a CoffeeScript language to JavaScript or inline images to data URLs. With loaders we can even import CSS files directly from our JavaScript modules. Plugins. Plugins are used for any other task that loaders can’t do. They provide us with a wide range of solutions about asset management, bundle minimization and optimization, and so on. Mode. Typically, when we develop our application we work with two types of source code — one for the development build and one for the production build. Webpack allows us to set which one we want to be produced by changing the mode parameter to development, production or none. This allows webpack to use built-in optimizations corresponding to each environment. The default value is production. The none mode means that there won’t be used any default optimization options. To learn more about the options webpack uses in development and production mode, visit the mode configuration page. How Webpack Works In this section we’ll examine how webpack works. Even a simple project contains HTML, CSS and JavaScript files. Also, it can contains assets such as fonts, images, and so on. So, a typical webpack workflow would include setting up an index.html file with the appropriate CSS and JS links, and the necessary assets. Also, if you have many CSS and JS modules which depend on each other, they need to be optimized and properly combined in one unit ready for production. To do all this, webpack relies on configuration. Although webpack 4 comes with reasonable defaults, for any non-trivial project you’ll need to provide a special configuration file webpack.config.js, which describes how the files and assets should be transformed and what kind of output should be generated. This file can quickly become quite monolithic, which makes it hard to understand how webpack does its job unless you know the main concepts behind its working. Based on the provided configuration, webpack starts from the entry points and resolves each module it encounters while constructing the dependency graph. If a module contains dependencies, the process is performed recursively against each dependency until the traversal has completed. Then webpack bundles all project’s modules into a small number of bundles — usually, just one — to be loaded by the browser. Getting Started Note: you can find the files for our project in the GitHub repo. Now that we have solid theoretical foundation, let’s implement it in practice. To start, we’ll create a new directory and switch to it. Then we’ll initialize a new project: mkdir learn-webpack cd learn-webpack npm init -y Next, we need to install webpack and webpack CLI locally: npm install webpack webpack-cli --save-dev Now, the content of the generated package.json should be similar to the following: { "name": "learn_webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.30.0", "webpack-cli": "^3.3.0" } } Besides bundling modules, webpack can be used as a simple task runner. We can create webpack tasks by including the name of our task followed by its instructions in the scripts section of the package,json file. Let’s try this now. Open package.json and change the scripts object to the following: "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode development", "build": "webpack --mode production" }, Within the scripts property, webpack allows us to reference locally installed npm packages by their names. We use that and the --mode flag to define dev and build tasks, which will run webpack in development (npm run dev) and production (npm run build) mode respectively. Before we test the tasks we’ve just created, let’s create a src directory and put an index.js file in it so that it contains console.log("Hello webpack");. Now we can already to run the dev task to start webpack in development mode: $ npm run dev > learn_webpack@1.0.0 dev C:\Users\User\Webpack\learn_webpack > webpack --mode development Hash: 5bb3bdc1efd7b7f4b627 Version: webpack 4.30.0 Time: 226ms Built at: 2019-04-16 17:48:32 Asset Size Chunks Chunk Names main.js 3.8 KiB main [emitted] main Entrypoint main = main.js [./src/index.js] 27 bytes {main} [built] Great! It works as expected. But to verify that we get the correct output, we need to display the result in the browser. To do that, let’s create an index.html file in the dist directory: <!doctype html> <html> <head> <title>Getting Started</title> </head> <body> <script src="main.js"></script> </body> </html> Now, if we open the file in the browser, we should see the Hello webpack message in the console. So far, so good. But writing our index.html file manually can be problematic in some cases. For example, if we change the name of our entry point, the generated bundle will be renamed, but our index.html file will still reference the old name. So, we’ll need to update our HTML file manually every time we rename an entry point or add new one. Fortunately, we can easily fix that with the html-webpack-plugin. Let’s install it now: npm install html-webpack-plugin --save-dev At this point, to activate the plugin, we need to create a webpack.config.js file in the root directory with the following content: const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { plugins: [ new HtmlWebpackPlugin({ title: "Webpack Output", }), ], }; As you can see, to activate a webpack plugin, we need to include it and then add it to the plugins array. If needed, we also pass options to the plugin. Let’s run our build now to see what will happen: $ npm run build > learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack > webpack --mode production Hash: e56a796f5ccfebcc8270 Version: webpack 4.30.0 Time: 1088ms Built at: 2019-04-16 20:44:47 Asset Size Chunks Chunk Names index.html 183 bytes [emitted] main.js 956 bytes 0 [emitted] main Entrypoint main = main.js [0] ./src/index.js 27 bytes {0} [built] Child html-webpack-plugin for "index.html": 1 asset Entrypoint undefined = index.html [2] (webpack)/buildin/global.js 472 bytes {0} [built] [3] (webpack)/buildin/module.js 497 bytes {0} [built] + 2 hidden modules Let’s open the index.html. As we can see, the plugin automatically creates an updated index.html file for us which uses the title option from the configuration: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Webpack Output</title> </head> <body> <script type="text/javascript" src="main.js"></script></body> </html> Let’s now expand our project and specify custom names for the entry and output properties. In webpack.config.js we add the following before the plugins property: entry: './src/app.js', output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, Now, we’ll create an src/component.js file: export default (text = "Hello webpack") => { const element = document.createElement("p"); element.innerHTML = text; return element; }; Next, we rename index.js to app.js to reflect our changes, and swap its content with the following: import component from "./component"; document.body.appendChild(component()); Now, let’s run webpack in production mode: $ npm run build > learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack > webpack --mode production Hash: 9f78936f8a2a21061f0b Version: webpack 4.30.0 Time: 1689ms Built at: 2019-04-17 23:43:40 Asset Size Chunks Chunk Names index.html 190 bytes [emitted] main.bundle.js 1.04 KiB 0 [emitted] main Entrypoint main = main.bundle.js [0] ./src/app.js + 1 modules 227 bytes {0} [built] | ./src/app.js 79 bytes [built] | ./src/component.js 148 bytes [built] Child html-webpack-plugin for "index.html": 1 asset Entrypoint undefined = index.html [2] (webpack)/buildin/global.js 472 bytes {0} [built] [3] (webpack)/buildin/module.js 497 bytes {0} [built] + 2 hidden modules Let’s examine and clarify the information from the webpack output. Beginning from the top, we see the hash of the build, webpack version, and the time it took to execute the build. Next, we see the files generated in the dist directory (index.html and main.bundle.js). Below them, we see the entry module (app.js) and its dependency (component.js). The output after Child html-webpack-plugin for "index.html": is related to the internal work of the html-webpack-plugin and we can safely ignore it. So now, in the dist folder, we have the newly generated bundle file main.bundle.js. If we open index.html in the browser, we should see Hello webpack displayed on the page. Also, if we check the source of index.html, we’ll see that the value of the src property in the script tag is updated to main.bundle.js. The post A Beginner’s Guide to Webpack appeared first on SitePoint.


Why the Highest Paid Developers “Fight” Their Coworkers

You're going to be asked to do it. At some point, if it hasn't happened already, your coworkers or your boss will ask you to do something foolish. Something you know will make things worse for you, your coworkers, maybe even the business itself. If you're like most developers, you do it anyway. That's what most will do, right? It's better to keep your head down, avoid making waves and simply do what you're told. Job security isn't a thing anymore, but that's one of the best things you can do to keep your job, for a while at least. This Common Mistake Creates a Career Handicap This is the problem. Most employees want to keep their jobs and their clients. They don't have the leverage or control they want over their own careers. They need their job. In fact, most people are terrified of losing their jobs. This has a cascading effect. Research shows the fear of losing your job creates job dissatisfaction and a lack of commitment at work. This, in turn, affects job performance, negatively increasing the likelihood that you will lose your job. It's a vicious cycle that seems to repeat itself over and over. But there's something worse than the fear of a job loss. It's the misplaced confidence or expectation of job security, the kind of confidence that crushes you when you're actually let go. Both of these issues are a problem, and both of these issues are continually ignored. Why is it a problem? Because 78 percent of employees live paycheque-to-paycheque. This includes workers making $100,000+ per year. This is the real reason why most employees have no leverage, no ability to say no. This is the reason most developers won't fight with their coworkers. Why Developers Need to Fight Their Coworkers What do I mean by "fight?" The post Why the Highest Paid Developers “Fight” Their Coworkers appeared first on SitePoint.


SitePoint Premium New Releases: Flask, Pug, ECMAScript, Linux + 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. Mastering Flask Web Development Second Edition Build modern, secure, production-ready web MVC apps and APIs using Python’s Flask framework. Utilize various extensions like Flask-JWT and Flask-SQLAlchemy to develop powerful applications. Deploy a Flask app on real-world platforms like AWS and Heroku on VMs or Docker containers. Read Mastering Flask Web Development Second Edition. React Native Blueprints Develop real-world Android and iOS apps with React Native, building fun projects from scratch while discovering more efficient techniques. Learn to build professional Android and iOS apps with your JS skills. Use Isomorphic principles to build mobile apps that offer a native user experience. Read React Native Blueprints. A Beginner’s Guide to Pug In this guide, we’ll demonstrate how to get up and running with Pug, a template engine for Node and for the browser. We’ll start by installing it, go over its basic syntax and then look at several examples of using JavaScript in Pug. Finally, we’ll explore a couple of Pug’s more advanced features. Read A Beginner’s Guide to Pug. ECMAScript Cookbook Become a better web programmer by writing efficient and modular code using ES6 and ES8. Learn to write asynchronous code and improve app readability. Explore advanced concepts such as closures, generators and Promises. Use design patterns to create structures to solve common issues. Read ECMAScript Cookbook. Linux Essentials, 2nd Edition Perfect for beginners, Linux Essentials Exam students, and those seeking a career in IT, this book presents task-based lessons on the basics of Linux, including distributions, types of apps, freeware, licensing, operations, navigation, command functions, user types, users and groups, and much more. Read Linux Essentials, 2nd Edition. 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 library for a spin. The post SitePoint Premium New Releases: Flask, Pug, ECMAScript, Linux + More appeared first on SitePoint.