Blog posts under the JavaScript category https://webdevstudios.com/category/javascript/ WordPress Design and Development Agency Mon, 15 Apr 2024 15:59:14 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the JavaScript category https://webdevstudios.com/category/javascript/ 32 32 58379230 Having Fun with Query Loop Block https://webdevstudios.com/2023/05/16/query-loop-block/ https://webdevstudios.com/2023/05/16/query-loop-block/#comments Tue, 16 May 2023 16:00:59 +0000 https://webdevstudios.com/?p=25658 The Query Loop block is a powerful tool that brings the WP Loop, a core WordPress function, to the block editor. Introduced in WordPress version 5.8 and continually updated and improved since then, the Query Loop block is a useful way to display a list of posts or other content in the block editor. In Read More Having Fun with Query Loop Block

The post Having Fun with Query Loop Block appeared first on WebDevStudios.

]]>
The Query Loop block is a powerful tool that brings the WP Loop, a core WordPress function, to the block editor. Introduced in WordPress version 5.8 and continually updated and improved since then, the Query Loop block is a useful way to display a list of posts or other content in the block editor. In this article, we will explore the usefulness of the Query Loop block and how to extend its capabilities.

To get started, we will create a plugin to store our code. The quickest way to create a plugin scaffold is by using the WP-CLI command npx @wordpress/create-block loop-patterns, which will generate the necessary files for us.

If you want more information on the create-block script, you can check out the WordPress documentation.

Query Loop Variations

WordPress provides block variations as a way for developers to create custom versions of core blocks. To get started, we will need to create some directories to store our code. We can do this by running a few commands in the terminal.

We begin by creating a simple block variation called simple-query, and adding a CSS folder to store minimal styles. We don’t want to change the theme styles already declared in the theme.json file. To add our code, we will edit the simple-query/index.js file.

We will use the registerBlockVariation() function to register our block variation. If you are unfamiliar with block variations, you can learn more about them here.

This code defines a constant called SIMPLE_QUERY, which is set to the string 'loop-patterns/simple-query'. This constant represents the name of a block variation that is being registered.

The wp.domReady() function is a WordPress function that is called when the DOM (Document Object Model) is fully loaded and ready for manipulation. Inside the wp.domReady() function, the wp.blocks.registerBlockVariation() function is called with two arguments: 'core/query' and an empty object {}.

The wp.blocks.registerBlockVariation() function is used to register a block variation. The first argument is the name of the parent block (in this case, 'core/query'), and the second argument is an object that specifies the properties of the block variation being registered. In this case, the object is empty, so no additional properties are being set for the block variation.

As previously mentioned, the registerBlockVariation() function takes two arguments: the first argument is the name of the parent block, and the second argument is an object that specifies the properties of the block variation being registered. Let’s review the properties of the object.

  1. name: This property specifies the name of the block variation being registered. In this case, the value of the name property is the constant SIMPLE_QUERY, which represents the string 'loop-patterns/simple-query'.
  2. title: This property specifies the title of the block variation. This title will be displayed to the user in the block editor. In this case, the value of the title property is 'Simple Query'.
  3. description: This property specifies a description of the block variation. This description will be displayed to the user in the block editor. In this case, the value of the description property is 'Displays a Simple Query'.
  4. return: This property is a function that specifies the conditions under which the block variation should be displayed to the user. In this case, the function returns true if the namespace variable is equal to SIMPLE_QUERY and the query.postType variable is equal to 'post'. Otherwise, the function returns false.
  5. icon: This property specifies the icon that should be displayed for the block variation in the block editor. In this case, the value of the icon property is 'edit-large', which represents a pencil icon.
  6. attributes: This property is an object that specifies the attributes (i.e., data values) that the block variation should have. In this case, the object is empty, so no attributes are being set for the block variation.

Block Attributes

The next step will be adding our block attributes. Let’s take a look at the Query Loop block attributes.

 

Based on the screenshots, we can add the following to the attributes object in our script:

The attributes object in this code defines the query parameters that will be used to retrieve posts from the WordPress database.

Here is what each attribute does:

  • perPage: The number of posts to be displayed on each page.
  • pages: The number of pages to be displayed.
  • offset: The number of posts to skip before starting to display posts.
  • postType: The type of post to be displayed (e.g., post, page, etc.).
  • order: The order in which the posts will be displayed (either asc for ascending or desc for descending).
  • orderBy: The criteria used to order the posts (e.g., date, title, etc.).
  • author: The ID of the author whose posts will be displayed.
  • search: A search term used to filter the posts that are displayed.
  • exclude: An array of post IDs to exclude from the query.
  • sticky: A value used to include or exclude sticky posts from the query.
  • inherit: A boolean value indicating whether the query should inherit the context of the current page.

These attributes can be used to customize the behavior of the query and fine-tune which posts are displayed.

Finally, we will build our template. We can use the innerBlocks property to build our template by creating nested blocks within the parent block.

In this case, the innerBlocks array has three nested blocks:

  1. The first nested block is an instance of the core/post-template block, which is a template block that can be used to display a single post. The second element of the array is an empty object {}, which represents the attributes of the block. The third element of the array is another array, which represents the content of the block. In this case, the content of the core/post-template block consists of two blocks: the core/post-title block and the core/post-excerpt block.
  2. The second nested block is an instance of the core/query-pagination block, which is used to display pagination links for a list of posts.
  3. The third nested block is an instance of the core/query-no-results block, which is displayed when a query returns no results.

This is what our final code will look like::

Register Our Scripts

Now let’s test our simple query to make sure it is reading our code correctly. To do this, we need to change how we register our scripts in the **loop-patterns.php**file. Replace the existing content with the following:

To make sure you are calling the script correctly, add the following to the src/index.js file:

And make sure that you’re calling the script correctly on src/index.js. Add this:

Let’s visit the block editor and check out our new block variation. See how it appears in the block editor and on the frontend of the site.

While our custom variation is simple, it’s a good starting point. Now that we have a better understanding of how to register a query loop variation let’s create a flip cards variation for the Query Loop block. To create a new flip-cards variation, we can follow the same steps we used to create the previous variation.

This code registers a new block variation for the core/query block calledflip-cards. The variation has a name, title, and description and is only active if the namespace is FLIP_CARDS and the postType attribute of the query object is 'post'. The variation also has a set of attributes, including a className, tagName, and queryobject.

The variation is scoped to the block inserter and does not contain any inner blocks.

Inner Blocks

For our inner blocks, let’s do the following:

This code defines an array of inner blocks for the flip-cards variation of the core/query block. The inner blocks include a core/post-template block, which is locked and has a specific className. The core/post-template block also contains a core/group block, which in turn contains a core/columns block. The core/columns block contains two core/column blocks, which each contain various blocks such as core/post-title, core/post-date, core/post-author, and core/post-excerpt.

The structure of the inner blocks creates a layout with flip cards, where each card has a front and backside. The front side of the card contains a featured image, and the back side contains the post title, date, author, and excerpt. The blocks are nested inside each other to create the desired layout and functionality.

If you’re having trouble understanding how to access the block’s attributes, a helpful resource is the block library on GitHub. Alternatively, you can view the block’s attributes by clicking the Code editor option under the Editor toolbar, or by referring to the attributes we registered earlier.

The same applies to all blocks, I found it very helpful when looking for the attributes.

Adding Styles

The finishing touch will be adding our styles, which are the following:

With all the pieces in place, we can now see the results of our custom query loop variation. In the block editor and on the frontend of the site, we should see:

I hope you’ve enjoyed this tutorial and have learned how to create custom query loop variations in the block editor. With these skills, you can give your content a unique look and feel and customize the Query Loop block to meet your needs. Thanks for following along, and I look forward to seeing what you create!

The post Having Fun with Query Loop Block appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2023/05/16/query-loop-block/feed/ 2 25658
Local Development with Node and Express https://webdevstudios.com/2021/05/06/local-development-with-node-and-express/ https://webdevstudios.com/2021/05/06/local-development-with-node-and-express/#respond Thu, 06 May 2021 16:00:51 +0000 https://webdevstudios.com/?p=23770 Create your Server If you are working with React and webpack, you probably or mostly never have to create your own local server. If you ever wonder how it works under the hood, here is a simple way to get a local server up and running in no time. Install Node First we need Node. Read More Local Development with Node and Express

The post Local Development with Node and Express appeared first on WebDevStudios.

]]>
Create your Server

If you are working with React and webpack, you probably or mostly never have to create your own local server. If you ever wonder how it works under the hood, here is a simple way to get a local server up and running in no time.

Install Node

First we need Node. You probably have node installed. If not, and you’re on a Mac use Homebrew:

View the code on Gist.

Your First Server

Create a index.js file:

View the code on Gist.

Then on our index.js :

View the code on Gist.

To learn more about the Node http package, use the following link to learn all about http.

Finally, run index.js with:

View the code on Gist.

Go to your browser and enter http://localhost:3000/ in your browser. You should see the text, ‘Hello Node.js.’

Request and Response

To have different responses based on different URLs, we now change our respond:

View the code on Gist.

Let’s restart Node: CTRL + C. Run  node index.js. Go to localhost:3000 and navigate the routes:

To see your request information, open developer tools/network/status. It will show the status code from the request.

What about adding HTML Files to our routes? In the same directory of index.js, create:

View the code on Gist.

With Emmet, it is as easy as typing ! or doc and hit the ENTER KEY. Your file will have the HTML code necessary to run. If you use Visual Code like me, support for Emmet snippets and expansion is built right into Visual Studio Code; no extension required.

Emmet takes the snippets idea to a whole new level. You can type CSS-like expressions that can be dynamically parsed, and produce output depending on what you type in the abbreviation. Emmet is developed and optimized for web developers whose workflow depends on HTML/XML and CSS but can be used with programming languages too. Bookmark this: Emmet Cheat Sheet.

Now, add a navigation. Let’s use Emmet one more time.

Between the body tags, go ahead and type ul>li*3>a and hit enter. This will create an unordered list with three items and a tags. Add your links, as seen in this screenshot, and then add a h1 tag on each of the pages named Homepage, About, Contact, and Page Not Found. Your files should look like this:

Let’s update index.js.

View the code on Gist.

Restart the server with CTRL + C and run  node index.js . Go to: http://localhost:3000; you’re now navigating your HTML files.

 

Express

Express is a minimal and flexible NodeJS web application framework that provides a robust set of features for web and mobile applications. Express provides a layer of abstraction to make handling web traffic and APIs easier. In short, Express did for NodeJS what Bootstrap did for HTML/CSS and responsive web design.

Some of the advantages of using Express are:

  • Almost the standard for Node.js web middleware
  • Simple, minimalistic, flexible, and scalable
  • Fast app development
  • Fully customizable
  • Low learning curve
  • Majorly focused on browsers, making templating and rendering an almost out-of-the-box feature

Before we install Express, we need to create a package.json file. On your root directory, run:

View the code on Gist.

If you’re not familiar with npm init and its flags, I recommend running npm help init for definitive documentation on these fields and exactly what they do.

Now that we have our package.json in our project. Let’s go ahead and install Express:

View the code on Gist.

Let’s refactor our index.js to work with Express:

View the code on Gist.

Previously we create a server and started with:

View the code on Gist.

We have to take care of importing http, fs , other packages, and also the request and response object; but with Express, we achieve the same thing.

Run CTRL + C and  node index.js . Check your terminal. It should now log from Express, your routes are probably broken.  We’ll take care of that next.

View the code on Gist.

Routing with Express

You define routing using methods of the Express app object that correspond to HTTP methods—for example, app.get() to handle GET requests and app.post() to handle POST requests.

The following code is an example of a very basic route.

View the code on Gist.

To learn more about Express routing click here. For now, let’s add routing to our app go to index.js.

View the code on Gist.

Express adds things like the sendFile method which makes it easier to write request handler functions.

That’s it! Run CTRL + C and node index.js and navigate within your app.

 

Serving Static Files

Express has this special function, app.use(), which mounts the specified middleware function or functions at the specified path. The middleware function is executed when the base of the requested path matches path. This special function, express.static(), is a built-in middleware function in Express. It serves static files and is based on serve-static.

What is middleware? Middleware is a software that bridges gaps between other applications, tools, and databases in order to provide unified services to users. It is commonly characterized as the glue that connects different software platforms and devices together.

View the code on Gist.

Create a directory:

View the code on Gist.

Add this code on your index.js file in the root of your app:

View the code on Gist.

To reference styles.css in index.html, add in index.html and on all your HTML files between the <head> in the following lines:

View the code on Gist.

Let’s make sure we are reading the styles and script; on your style.css add:

View the code on Gist.

In your index.js, be sure that this is the new index.js the one on our public folder on the js directory, and is not our root index.js.

View the code on Gist.

That’s it! You have an app running locally with Node and Express.

We learned how to install and run a Node application locally and leverage it with Express. We also learned how to serve static files with express.static().

Automatic Server Restart with Nodemon

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server, making it perfect for development. We have been starting and stopping our server each time we make a change on index.js, but with Nodemon, we don’t have to that anymore.

Let’s install Nodemon: npm i nodemon --save-dev. Now update your package.json.

View the code on Gist.

So instead of node index.js, we now run our app with npm start.

I hope this article helps you understand what happens under the hood on some of the most popular JavaScript bundlers.

The post Local Development with Node and Express appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/05/06/local-development-with-node-and-express/feed/ 0 23770
Let’s Get Ready to Rumble! Composer vs npm https://webdevstudios.com/2020/09/03/composer-npm/ https://webdevstudios.com/2020/09/03/composer-npm/#respond Thu, 03 Sep 2020 16:00:20 +0000 https://webdevstudios.com/?p=22738 TL;DR? NPM 🥊 Composer 👊 npm install (libraries go in node_modules, executables in node_modules/.bin) composer install (libraries go in vendor, executables in vendor/bin) npm install --production composer install --no-dev npm install --package-lock-only composer update --lock npm install <package> composer require <package> npm install <package> --save-dev composer require --dev <package> npm install -g <package> composer global Read More Let’s Get Ready to Rumble! Composer vs npm

The post Let’s Get Ready to Rumble! Composer vs npm appeared first on WebDevStudios.

]]>
TL;DR?
NPM 🥊 Composer 👊
npm install (libraries go in node_modules, executables in node_modules/.bin) composer install (libraries go in vendor, executables in vendor/bin)
npm install --production composer install --no-dev
npm install --package-lock-only composer update --lock
npm install <package> composer require <package>
npm install <package> --save-dev composer require --dev <package>
npm install -g <package> composer global require <package>
npm update composer update
npm update <package> composer update <package>
npm outdated composer outdated
npm run <script-name> composer run-script <script-name>

The Complete Picture

As developers, we’re used to saying, “It works on my machine.” A decade ago, this phrase was reserved for snarky conversations with your friendly quality assurance person or the product owner who is testing a feature.

As our technology tooling has become more advanced (read: more complex), I’ve seen it come up as inter-developer conversation, frequently between a frontend and backend engineers:

Composer and Node package manager (npm) are the de-facto package managers for PHP and JavaScript. We use them every day at WebDevStudios. Let’s help each other get to know their similarities and their differences, as both tools can do unexpected things that you may not realize.

Init

While initializing a project isn’t the most common command, it’s useful to cover it first; in case you want to try to initialize a Composer or npm project in an empty directory.

$ composer init

Composer will interactively ask you some questions about your PHP project including: package name, description, package type, etc. Newer versions of Composer will prompt you to add the vendor directory to your .gitignore file. You should do this!

You can also just create your own composer.json file. Here’s an example minimal composer.json:

{
    "name": "webdevstudios/composer-vs-npm",
    "description": "php side of composer-vs-npm",
    "license": "GPL-3.0-or-later"
}

npm has the same command:

$ npm init

It will also interactively ask you a few questions about your JavaScript project including: package name, description, license, etc. After gathering this info, it will create a package.json file.

You can instead create a package.json file yourself. A minimal package.json is just {}, but npm will warn you if you don’t have these fields:

{
  "name": "@webdevstudios/composer-vs-npm",
  "description": "js side of composer-vs-npm",
  "license": "GPL-3.0-or-later",
  "repository": "https://github.com/WebDevStudios/composer-vs-npm"  
}

Init Best Practices

For the npm package name, it’s a good idea to add a scope using the @ symbol, your organization name, and a slash before the package name. While it’s not required like Composer’s vendor name, it will help group your packages together.

npm does not offer to create an entry in .gitignore for the node_modules directory, but you should.

You can validate your composer.json file format by running:

$ composer validate

I recommend not including version in your composer.json. It’s just one more thing that developers will forget or ignore. Let your version numbers be managed through tagging in your version control software.

npm requires a version entry in package.json only if you’re publishing your package. If you’re publishing your package, make sure keeping this up to date is part of your workflow. Otherwise, I suggest to omit it.

Both Composer and npm use the same license strings. A license entry is not strictly required, but both will print a warning, if you don’t include it.

Saving Dependencies

I’m getting a little ahead of myself because we’re going to talk about npm install before the Install section below, but just bear with me. In Composer land, telling it that your project relies on a library is done by requiring it.

$ composer require <vendor>/<name>

This will instruct Composer to add an entry to the require section of your composer.json file, install the package (usually in a vendor directory), and create and/or update a composer.lock file with info about the version it installed.

npm does the same thing, but with their install command:

$ npm install <package>

This will instruct npm to add an entry to the dependencies section of your package.json file, install the package (in a node_modulesdirectory), and create and/or update a package-lock.json file with info about the version it installed.

Saving Options

You may have PHP or JavaScript dependencies that are only needed for development, and aren’t needed to use your project when it’s deployed. You can specify that those packages are installed as development dependencies:

$ composer require --dev <vendor>/<name>
$ npm install <name> --save-dev

Both Composer and npm can require specific versions of a package:

$ composer require <vendor>/<name>:<version>
$ npm install <name>@<version>

If you omit the version number, they’ll both specify the latest stable version with a carat (^) pre-pended. If you require lodash via npm, it will specify "lodash": "^4.17.20" in your package.json file. This means if you were to tell npm to update Lodash, it would upgrade to newer versions up to the next major version—5.0.0. If you ever get unexpected results from version numbers, you can use these excellent semantic versioning (semver) tools to test:

Install

As the “Dad Joke Dog” meme explains above, the most common command to run is install.

$ composer install

Running this in a folder that has a composer.json file will instruct composer to read that file (along with composer.lock if present) and install any requirements specified.

If the composer.lock file is present, it will install the exact versions specified by that file, even if a newer version exists. If there’s no composer.lock file, composer will install the latest packages according to the version constraints in composer.json and create a composer.lock file with those versions.

Usually packages will go into a vendor directory, next to the composer.json file.

$ npm install

Running this in a folder that has a package.json file will instruct npm to read that file (along with package-lock.json if present) and install any requirements specified.

If the package-lock.json file is present, npm (similarly) will install the exact versions specified by that file, even if a newer version exists. If there’s no package-lock.json file, npm will install the latest packages according to the version constraints in package.json and create a package-lock.json file with the exact versions.

Installing without development dependencies

To install packages without the development dependencies, like you would for a production environment, run either of these commands:

$ composer install --no-dev
$ npm install --production

This will skip installing require-dev or devDependencies for Composer or npm (respectively).

Update

This is one of those sections where I like to ask:

Are you sure you want to do this?

$ composer update
$ npm update

I like to ask are you sure because when you don’t supply any arguments to update, Composer and npm have the potential to make a lot of changes that you may not have intended. Both will use the version constraints to update your specified dependencies (including dev dependencies) and it will update the child dependencies of the packages, too. So, if your version constraints are fairly “loose,” a lot of stuff is going to get updated, possibly some things you didn’t intend.

A more focused approach would be to upgrade one specific package, not all of them. Like this:

$ composer update composer/installers
$ npm update lodash

If you’re curious what is out of date, and what would be updated if you ran the update command without any arguments, you can run an outdated report instead:

$ composer outdated
$ npm outdated

Other useful commands

If you change something in your composer.json file that is unrelated to the version constraints—like reordering the required packages—Composer will complain that your composer.lock file is not up to date. To update just the content-hash part of the composer.lock file without updating any package versions, run:

$ composer update --lock

You can do the same thing with npm:

$ npm install --package-lock-only

Conclusion

As you can see, there are several commands that do the same thing and look the same in both Composer and npm. However, there are also commands that do the same thing but look very different.

It’s good to make sure you know what that command is going to do before you do it, so you don’t have to undo things you didn’t want to happen. 😬

Are there any other commands you use often that I missed? Let us know in the comments.

The post Let’s Get Ready to Rumble! Composer vs npm appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/09/03/composer-npm/feed/ 0 22738
Post Event Report: Jamstack Conf Virtual 2020 https://webdevstudios.com/2020/06/18/jamstack-conf-virtual-2020/ https://webdevstudios.com/2020/06/18/jamstack-conf-virtual-2020/#respond Thu, 18 Jun 2020 16:00:10 +0000 https://webdevstudios.com/?p=22388 Jamstack Conf is a two-day celebration of the next generation of web apps, where the JAMStack community and ecosystem come together to learn, connect, and create. Conference attendees range from frontend and full-stack engineers to web agencies, all ready to push the boundaries of tomorrow’s web architecture. This year for the first time, a first Read More Post Event Report: Jamstack Conf Virtual 2020

The post Post Event Report: Jamstack Conf Virtual 2020 appeared first on WebDevStudios.

]]>
Jamstack Conf is a two-day celebration of the next generation of web apps, where the JAMStack community and ecosystem come together to learn, connect, and create. Conference attendees range from frontend and full-stack engineers to web agencies, all ready to push the boundaries of tomorrow’s web architecture. This year for the first time, a first virtual version with talks and workshops was held on May 27th-28th, and I was there.

But first, what is the JAMStack?

In the JAMStack, JavaScript (JS) is responsible for giving the necessary dynamism to the web page. Of course, the JS runs 100% on the client. There is no restriction on the style of the code or the JS library/framework that can be used. All the data and business logic that the web requires must be accessed via APIs. A set of markdown templates define how this data will be displayed.

As you can see, the JAM architecture is very different from what we are used to seeing if we use a pure WordPress or Drupal type CMS, where each individual client request involves a query to the CMS database to retrieve the data to display and render them with the corresponding template. At JAM, the website is pre-generated.

What does this mean?

It has many advantages, such as greater speed, security, price, and user experience. The million-dollar question is, then, what do I do when the data that my website has to show changes?

No problem. At JAM, the web is not static but is pre-generated. You can regenerate the web as many times as you want so that the data is always updated.

Once regenerated, it behaves like a static web. Simplifying, the web follows a continuous deployment process just like you already do (or should do) with the code. Services like Netlify help you automate this process. Note that you can even continue using WordPress as a backend if you want, but seen as a headless CMS, which we will access during the rendering process of the web prior to its deployment

The Jamstack Conf

That said, the Jamstack Conf is the must-attend event for anyone building the next generation of web applications. The event was hosted by Netlify, and the Keynote was by Matt Biilman, who gave us a brief tour about the state of the JAMStack and why it is so important, especially in these times, because web access to information is a really big thing in this global pandemic and situation. The web has always been central to the idea of ​​sharing and accessing information from all over the world, from all kinds of devices and places.

For example, Matt mentioned that for the outbreak of 2003,  23 articles and studies were published. For the emergence of the COVID-19, there are currently more than 10,000 articles on the virus and even more to come. This is a huge volume of information. It’s a truly global phenomenon with researchers all over the world talking to each other, communicating online, and sharing information with the public and researchers.

Matt talked to us about how the JAMStack has helped researchers and gave the example of a website that took advantage of this technology. The COVID Tracking Project was created to share data from all over the US, making it available to anyone with an interest. It’s based on a modern workflow around Github and Git, with people from all over the web industry contributing. It’s a project that reaches places like the White House or the New York Times, to public institutions. The COVID Tracking Project has been widely circulated and has had more than 35 million unique visitors. That blows my mind how much a server or servers could cost to handle 35 million unique visitors or days with more than a hundred million requests.

Matt also highlighted the great difference in internet speeds, citing as an example that the speed of bandwidth increased by 20.65% but also increased the speed difference of users by up to 125 times more, between places with the slowest speed and the fastest. Matt closed his presentation by mentioning that if you were a web developer back in the 90s, you actually had to think about physical servers. You had to think about power cords and stuff.

On the other hand, you would never have to deal with client-side optimizations, client-side builds, or responsive design. So, as the web has progressed and the demands of the experiences and the devices accessing sites have gone up, the idea behind JAMStack had to sort of build layers of abstraction that take some of this complexity away, making it possible for a developer to work without considering those lower layers of the stack. I’m thankful for it!

Then it was time for the State of the JAMStack. This year, they surveyed over 3,000 web developers, both Netlify users and not, both JAMStack fans and not, about how they are building sites in 2020. To see the results, visit State of the Jamstack.

Q&A, Expo & Networking

At Jamstack Conf, there was also time to meet attendees and sponsors. There were video rooms; I loved it! Thanks to that, I was able to see first-hand several interesting new products, such as imgIX. This image processing and optimization API transforms, optimizes, and caches your entire image library using simple URL parameters, various headless CMS, such as Strapi, Prismic, or those already known, such as Sanity and the Algolia search engine.

Fireside Chat

After the break, it was time for one of my favorite talks: Harper Reed, former Head of Commerce at Braintree, and Frances Berriman. In 2011, Harper served as Chief Technology Officer for Barack Obama’s 2012 re-election campaign. Together, he and Frances talked about various topics, such as the beginning of JavaScript, libraries, and the future of JAMStack.

Lightning Launch

Netlify’s David Calavera CTO introduced the new Netlify Edge Handlers. Then it was Renaud Bressand’s turn to show us how to use Prismic with Nuxt.js.

Tom Preston-Werner presented a demo of RedwoodJS. RedwoodJS is bringing full-stack to the JAMStack! Built on React, GraphQL, and Prisma, Redwood is an opinionated, full-stack, serverless web application framework that will allow you to build and deploy JAMStack applications with ease. Imagine a React frontend, statically delivered by CDN, that talks via GraphQL to your backend running on AWS Lambdas around the world, all deployable with just a Git push. After that interesting talk, Erin Kissane told us more about The COVID Tracking Project.

Internet consumers in the emerging market are accessing your web products differently. Yes, there is fast growth, but the bar is still low. Christian Nwamba in his session walked us through the path of internet users in Sub-Saharan Africa and how JAMStack can help by providing a better experience.

Celebrating JAMStack

Overall, the conference had many helpful topics and showed the strength of the stack. For lovers of JAMStack, like me, it was a conference that fulfilled all my expectations. I wanted more, and I hope to be able to be present at the next Jamstack Conf, which will be October 6-7 in San Francisco.

If you want to relive the first Jamstack Conf Virtual, videos of talks are available on the official JAMStack channel.

The post Post Event Report: Jamstack Conf Virtual 2020 appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/06/18/jamstack-conf-virtual-2020/feed/ 0 22388
WordPress Block Development Made Easy https://webdevstudios.com/2020/06/16/wordpress-block-development/ https://webdevstudios.com/2020/06/16/wordpress-block-development/#respond Tue, 16 Jun 2020 16:00:38 +0000 https://webdevstudios.com/?p=21966 WordPress block development can be daunting. It’s already intimidating enough that you need to know ReactJS, you also need to install and configure tools like webpack, Babel, and ESLint. Here at WebDevStudios, we like to build things; and we love to do so conveniently and efficiently. That’s why we built a scaffolding tool that sets Read More WordPress Block Development Made Easy

The post WordPress Block Development Made Easy appeared first on WebDevStudios.

]]>
WordPress block development can be daunting. It’s already intimidating enough that you need to know ReactJS, you also need to install and configure tools like webpack, Babel, and ESLint.

Here at WebDevStudios, we like to build things; and we love to do so conveniently and efficiently. That’s why we built a scaffolding tool that sets up everything you need to focus on building your block! Meet @webdevstudios/create-block.

Requirements

You need to have the latest Node and NPM installed. I highly recommend that you use NVM to easily manage and switch between Node versions.

Getting started

Navigate to wp-content/plugins and run the command below. Grab yourself a cup of coffee or tea while waiting for the scaffolding process to finish.

$ cd wp-content/plugins
$ npm init @webdevstudios/block [Namespace]/[BlockName]

Where [Namespace] and [BlockName] can be anything you want.

What’s inside?

Immediately, you can see the scaffolded plugin in your dashboard.

The scaffolded plugin also has a demo block created for you.

Inside the plugin files

I won’t go into details on each of the files and directories but to give you a general idea:

build/ is where the compiled assets are located. The JS and CSS files here are the ones enqueued (loaded) in your WordPress. Build/compiled files are auto-generated and shouldn’t be edited directly.

node_modules/ is where the npm packages are installed.

src/ is where you’ll create all your files.

vendor/ is where the composer packages are installed.

todo-block.php is the main plugin file.

If you are not familiar with composer.json, package.json, webpack.config.js, and the other files, it’s alright. That’s the beauty of our scaffolding tool. All of these are pre-configured, and you don’t need to touch these files, unless necessary.

Inside src/ is the block/ directory. This is where we will create our block(s). Inside block/ you’ll see rich-text/, which is the demo block.

Inside src/block/rich-text are the following files:

edit.js describes the structure of your block in the context of the editor. This represents what the editor will render when the block is used. Read more here.

editor.scss are the styles rendered in the editor. If you are not familiar with `.scss`, you can still treat it as CSS. `.scss` is CSS in steroids, hence the additional `s`. Kidding aside, it’s Sass. I highly recommend that you start using it.

index.js is where your block is registered using `registerBlockType()`. Read here for more info.

save.js defines the way in which the different attributes should be combined into the final markup, which is then serialized into post_content. For most blocks, this is how the block appears in the frontend. Read more here.

style.scss are styles rendered in both editor and the frontend.

Included commands

npm start – Make sure that you are running this command during development. Doing so will automatically build/compile your assets as you develop.

npm run build – Build your files.

npm run lint:css – Run linting to your stylesheets.

npm run lint:js – Run linting to your JS files.

npm run lint:php – Run linting to your PHP files.

Our scaffolding tool uses our WDS Block Starter. If you have any questions, find any bugs, or want to contribute to our scaffolding too, feel free to go over to the GitHub repository.

The post WordPress Block Development Made Easy appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/06/16/wordpress-block-development/feed/ 0 21966
StorybookJS and Why You Should Use It https://webdevstudios.com/2020/04/09/storybookjs/ https://webdevstudios.com/2020/04/09/storybookjs/#respond Thu, 09 Apr 2020 16:00:53 +0000 https://webdevstudios.com/?p=21637 What is Storybook? Storybook is a user interface (UI) development environment and playground for UI components. The tool enables developers to create components independently and showcase components interactively in an isolated development environment. Storybook supports many different frontend view layers. React, Vue, Angular, Mithril, Marko, HTML, Svelte, Meteor, Ember, Riot and Preact are currently supported. Read More StorybookJS and Why You Should Use It

The post StorybookJS and Why You Should Use It appeared first on WebDevStudios.

]]>
What is Storybook?

Storybook is a user interface (UI) development environment and playground for UI components. The tool enables developers to create components independently and showcase components interactively in an isolated development environment.

Storybook supports many different frontend view layers. React, Vue, Angular, Mithril, Marko, HTML, Svelte, Meteor, Ember, Riot and Preact are currently supported.

Why Is It Useful?

As developers, our goal is usually to build software incrementally, with the goal of new features being written in a modular manner. To ensure that our code operates correctly, we usually capture its behavior in a set of unit tests. These tests exercise our code in an isolated way. However, when we later go to manually test our components, it’s typically done within the context of the full website.

Storybook allows you to see and interact with your components in an isolated way, similar to how unit tests scope the testing of your component code.

The most important aspect of it is that Storybook gives us a great way to visually test our application during construction. The ‘stories’ will help ensure we don’t break our task visually, as we continue to develop the app.

Key Benefits

  • Isolation
  • Props mocking
  • Action logger
  • Hot reloading
  • Runs anywhere
  • Showcase your components

Who Uses Storybook

Over 30,000 projects use Storybook. It powers frontend development for teams at Airbnb, Lyft, Slack, Twitter, and thousands of more companies. It’s used to build top design systems like Shopify Polaris, IBM Carbon, Salesforce Lightning, and the WordPress Gutenberg project.

A screencast video of Gutenberg Storybook Playground.
The Gutenberg Project has a very nice playground setup with Storybook. Visit the Gutenberg GitHub.

Quick Guide to Get Up and Running

The easiest way to get started with Storybook is to use the automated command-line tool, a CLI that scans your app and will make the changes required to get storybook working. The tool inspects your package.json to determine which view layer you’re using.

If the CLI doesn’t detect your project type, it will prompt you to choose manually your project type.

Start Storybook with:


Visit http://localhost:6006/ and check your newly created Storybook.

That’s all you need to set up and run your storybook dashboard. A folder called storybook/ was created in your root project. That folder contains all the setup generated by the Storybook CLI.

What’s Next?

Now that we have our Storybook ready, it’s time to add stories.  We have to remember that a Storybook is a collection of stories; one story for each of our components. The official docs refer to each story as a function that returns something that can be rendered to screen.

You will find on your local installation that you also have a new directory named stories/ . There are many ways to name and place the scheme. Storybook recommends placing it alongside the component.

I like to keep it outside src/ directory, keeping main project files separated (and by default, when running the CLI, you will get a stories directory).

 

The most convenient way to load stories is by filename. Your stories files are located in the stories/ directory. You can use the following snippet in the storybook/main.js:

So for example, if you have a Buttonnamed Button.js, you would  name your story Button.stories.js.

This is the basic example of stories for a Button component:

Now that you have set up your Storybook, it is time to create your own.

Why Should You Be Using It?

Alright, let’s say you are starting your project. You enter in your src folder and create a new file called Modal.js. After that, you call this component inside your index.js file and open your browser to check the component. You’ll repeat it every time you create a new one!

Okay, maybe that process isn’t an issue, if you are working on a small project. But what if it is a big project, or you are working with a remote team? If one of your team members needs to use your component, this person will need to open your Modal.js file, check the properties, styles, actions, etc. Eventually, you’ll learn that it’s a long process that takes time. However, Storybook helps you and your team to easily manage components with a single source of truth.

Now, you’ll be able to use Storybook to quickly prototype, more easily communicate with your team, and envision how Storybook can be extended to fill other gaps in your process. The official docs and LearnStorybook.com are great resources.

Use this living design system that updates with production to optimize your development process.

The post StorybookJS and Why You Should Use It appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/04/09/storybookjs/feed/ 0 21637
A Better, Cleaner Way to Render HTML with JavaScript https://webdevstudios.com/2019/12/12/render-html-with-javascript/ https://webdevstudios.com/2019/12/12/render-html-with-javascript/#comments Thu, 12 Dec 2019 17:00:35 +0000 https://webdevstudios.com/?p=21492 As a team of WordPress developers, we often stumble upon a task where we need to request a set of data using AJAX and render it to the browser. Most of the the time we do it like this: View the code on Gist. It works. However, it’s difficult to maintain this code, and most Read More A Better, Cleaner Way to Render HTML with JavaScript

The post A Better, Cleaner Way to Render HTML with JavaScript appeared first on WebDevStudios.

]]>
As a team of WordPress developers, we often stumble upon a task where we need to request a set of data using AJAX and render it to the browser.

Most of the the time we do it like this:

View the code on Gist.

It works. However, it’s difficult to maintain this code, and most of the time, the HTML markup we need to use is much more complex than the example above. As more updates and changes occur in the markup, we find it increasingly difficult to work with this code.

Enter wp.template

If you are familiar with Underscore.js or {{ mustache }}, wp.template is an underscore-based JavaScript templating helper shipped with WordPress.

So, how do we use it?

Create and render your HTML markup template

View the code on Gist.

Just with this, we can immediately see how easy it is to maintain our HTML markup.

Notes

1. It is important that the HTML markup template is wrapped with <script type=“text/html” id=“tmpl-[TEMPLATE-NAME]”></script>.
2. The id needs to be prefixed with tmpl-.
3. data is the variable passed to the template from the JavaScript. You’ll see this shortly.
4. JavaScript logic goes inside <# #>.
5. <# _.forEach() #> is an Underscore function. See Underscore.js.
6. Use {{ }} for escaping output.
7. Use {{{ }}} for unescaped output. Using {{ }} with data containing markup will convert the tags to HTML entities. So for example, if the data is <img src=""/> and we indeed want to render the image, we need to use {{{ }}}.

Load wp-util

The code for wp.template is inside wp-util, so we need to make sure that wp-util.js is loaded.

You can do this by adding wp-util as a dependency of your JavaScript. Like this:
wp_enqueue_script( 'custom_js', plugins_url( 'js/custom.js', __FILE__ ), [ 'jquery', 'wp-util' ] );

The JavaScript

View the code on Gist.

A few more notes…

1. We omit tmpl- in wp.template( 'display-posts' ).
2. The data we pass to display_posts_template() is the data variable we use in our template.

Conclusion

While we used <# _.forEach() #> in our example, it is a good idea to minimize the JavaScript logic in your template. The goal is to separate the “view” and “logic.”

For example, you can approach our example like this:

JavaScript

View the code on Gist.

Template

View the code on Gist.

wp.template is a good tool to create clean and maintainable code. Another advantage of using this technique is you don’t need to modify your JavaScript when you modify your HTML template. As a developer, it means no re-compiling / bundling / minifying / purging of JavaScript cache is needed.

What do you think? Will these tips help you with a better, cleaner way to render HTML with JavaScript? Leave us a comment below. Need a team to offer up solutions like this for your website project? Contact us today.

The post A Better, Cleaner Way to Render HTML with JavaScript appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/12/12/render-html-with-javascript/feed/ 1 21492
Creating, Extending, and Upgrading Custom ACF Fields That Use Select2 https://webdevstudios.com/2019/09/17/acf-fields-that-use-select2/ https://webdevstudios.com/2019/09/17/acf-fields-that-use-select2/#comments Tue, 17 Sep 2019 16:00:27 +0000 https://webdevstudios.com/?p=20970 Advanced Custom Fields (ACF) has been around for quite a while now, and it’s super popular. We’re on version 5.x now, and the earliest dated reference documentation I could find was for ACF 2.0 in 2011. There have been some bumps along the way. One of the more recent issues was compatibility of the Select2 Read More Creating, Extending, and Upgrading Custom ACF Fields That Use Select2

The post Creating, Extending, and Upgrading Custom ACF Fields That Use Select2 appeared first on WebDevStudios.

]]>
Advanced Custom Fields (ACF) has been around for quite a while now, and it’s super popular. We’re on version 5.x now, and the earliest dated reference documentation I could find was for ACF 2.0 in 2011. There have been some bumps along the way.

One of the more recent issues was compatibility of the Select2 JavaScript library versions. It was mostly because two other popular plugins, Yoast’s WordPress SEO and WooCommerce, also use Select2. What is Select2? It’s the kick-ass library that lets you transform boring dropdowns to amazing searchable and formattable ones:

A screen grab image of a searchable time zone dropdown menu.

So what’s the big deal with ACF? Well, Select2 has gone through some major revisions as well, most notably the latest Select2 Version 4, which is not backwards compatible with Select2 version 3.x. So, if ACF brings in Version 4 and WooCommerce brings in Version 3, we’ve got problems.

Thankfully, ACF came up with an elegant way to deal with these incompatibilities by checking to see if another plugin had enqueued Version 3 and falling back to using a Select2 Version 3 adapter.

View the code on Gist.

Future-proof it or just fix it?

So, what does this have to do with custom ACF fields? Well, in my case there was an old custom-built ACF field that used Select2. To add the Select2 library to the dropdown, it used a JavaScript call to acf.add_select2() to add it. If you notice in the gist above, acf.newSelect2() was added in ACF 5.6.5, and it replaces acf.add_select2(). In the future, how can we avoid running into this problem? In practice, there are two options:

  1. Extend an existing ACF field that is close to what you want to do.
  2. Create a new (or updating an existing) custom field and use ACF to add Select2.

Your first option is the best one. Here’s why: it simplifies your code investment by leveraging as much as possible from ACF. But, I’m also including the quick-fix instructions specific to the Select2. That way, if you have an existing field that you just need to get working for the time being, you can do that as well.

Option 1: Simplify by extension

One of the fields I needed to fix that used acf.add_select2() was strikingly similar to an existing ACF field—the relational field called Taxonomy. The built-in ACF Taxonomy field also uses Select2. The only difference between the custom field that needed repair and the built-in one is that the custom field would display terms from multiple categories, instead of just one. I had an a-ha moment on a call with Corey Collins when he suggested aloud to let ACF handle the hard work and to just tweak what I needed. Brilliant idea, Corey!

The custom field used to look like this:

View the code on Gist.

Because the AcfFieldMultipleCategories class was essentially a copy of class-acf-field-taxonomy.php, it was almost 600 lines of code.

Instead of extending acf_field, I was able to instead extend acf_field_taxonomy and reduce the PHP code by half and get rid of the custom JavaScript entirely.

View the code on Gist.

What’s different?

Here’s a brief breakdown of the things that are different in the AcfFieldMultipleCategories class and why. You can compare much of the code above to what’s in class-acf-field-taxonomy.php for reference.

  1. The class doesn’t get defined until init. This is because ACF doesn’t load the parent acf_field_taxonomy class right away.
  2. Using initialize instead of __construct: ACF 5.6.0 switched to using initialize instead of __construct so I wanted to follow suit. Our class calls parent::initialize() to get all of the defaults from the taxonomy field, then sets only the fields we want to override.
  3. AJAX actions for wp_acf: These actions are present on the parent, but when they’re registered, they reference a specific instance of an object—the parent acf_field_taxonomy class. We redefine them here to get called on our AcfFieldMultipleCategories instance.
  4. Extra CSS classes in wrapper_attributes: We need our custom field to be rendered with a CSS class of acf-field-taxonomy. This is what the ACF Select2 library is looking for to attach to fields. Select2 will behave exactly how it would on a taxonomy field; we’re just changing the query that happens on the back end.
  5. get_ajax_query has been overridden: It gets called from the parent ajax_query method. We override this to get a result set of terms from multiple taxonomies.
  6. load_value has been overridden and simplified to remove filtering.
  7. render_field has been overridden and simplified to only render a select field because that’s the only option we’re allowing.
  8. render_field_select has been overridden to call a custom get_term_by_id function.
  9. render_field_settings has been overridden to remove the Appearance setting (remember we only want it to display a dropdown). We also removed the Create Terms option, as we won’t be saving any new terms because they’re coming from multiple taxonomies.

Is it a lot? Sure, but it’s far less duplication than before and through simplification, making it less prone to bugs and errors. But if that’s still too much, can you take the easy way out…

Option 2: Just update Select2 calls

This option is an easier short-term solution but may postpone further compatibility issues. Just switch any calls from add_select2 to newSelect2. Any parameters to that function that were previously in snake_case need to be changed to camelCase. Here’s a diff of one that I updated:

-		acf.add_select2( $select, {
+		acf.newSelect2( $select, {
 			ajax: 1,
- 			ajax_action: "acf/fields/post_object/query",
- 			allow_null: 0,
+			ajaxAction: "acf/fields/post_object/query",
+			allowNull: 0,

That’s it. I chose this option for a different and far more complex custom ACF field. It had four inputs in one field, which is nothing like any built-in fields. This one is just going to stay as-is and will try to follow the ACF JavaScript conventions.

Getting Permission

When possible, I prefer the first method of doing things because it’s a better long term solution. You can do Option 2 in less than an hour and then still have time left over to convince your manager that Option 1 is better for the long term. Get some time scheduled to fix it the right way, and it’s a win-win for you and your project.

The post Creating, Extending, and Upgrading Custom ACF Fields That Use Select2 appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/09/17/acf-fields-that-use-select2/feed/ 1 20970
How to Use the Observable Pattern in JavaScript https://webdevstudios.com/2019/02/19/observable-pattern-in-javascript/ https://webdevstudios.com/2019/02/19/observable-pattern-in-javascript/#comments Tue, 19 Feb 2019 17:00:30 +0000 https://webdevstudios.com/?p=19636 Lately, I’ve been trying to become more familiar with design patterns. One thing I’ve realized along the way is that it’s not easy to recognize where a specific pattern might be useful. It usually comes down to having that light bulb moment where you suddenly say to yourself “Hey! This might be a good place Read More How to Use the Observable Pattern in JavaScript

The post How to Use the Observable Pattern in JavaScript appeared first on WebDevStudios.

]]>
Lately, I’ve been trying to become more familiar with design patterns. One thing I’ve realized along the way is that it’s not easy to recognize where a specific pattern might be useful. It usually comes down to having that light bulb moment where you suddenly say to yourself “Hey! This might be a good place to use a certain design pattern.”

Define the problem.

Since design patterns are used to solve specific problems in software, let’s try to define such a problem and work to solve it using a design pattern in JavaScript.

With the rise of frameworks like React, we often hear about ‘application/component state.’ When the state is updated, components will re-render accordingly. In React, components are just a representation of what the user interface should look like.

What if we wanted to try and implement that same sort of functionality using only vanilla JavaScript? There are any number of ways to do it, but in our case, let’s explore how using a design pattern could help with our implementation.

So, let’s define the problem we are trying to solve: we need to be able to update multiple page elements when our application state changes.

In this post, we will build out a little app that allows you to add users to a list. This app will use state; so we will use the observer pattern to notify the elements that need updated when that state changes.

What is application state?

In JavaScript, state is typically just an object that holds data your application depends on.

For example, maybe you have a small app that displays a list of items it retrieves from an external API. When the app loads, it makes sense to make the API call once and store the data in app state. The app could then render based on changes to its state.

The Observer Pattern

According to Wikipedia:

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

The observer pattern defines a one-to-many relationship. When one object updates, it notifies many other objects that it has been updated.

It’s easy to get tripped up with the subject and observer terms used in the definition above. It took me a while to wrap my head around it.

Here is a brief explanation for each:

  • subject – This is the object that will send out a notification to all of the ‘observers’ who want/need to know that the subject was updated. In our case, the subject will be the application state object.
  • observers – These are the objects that want to know when the subject has changed. In our case, these will be the page elements that need to update when the application state changes.

On a side note, the observer pattern is similar to another very popular design pattern in JavaScript, the pub/sub pattern.

Implementation

When implementing design patterns, there is often a contract that needs to be followed in order for the implementation to be correct.

What do I mean by contract? Well, in a more object-oriented language like PHP, there may be specific interfaces that the subject and observer classes need to implement. Those interfaces would in turn force any class that implements them to have the methods specified in the interface.

In JavaScript, we don’t have access to interfaces; and for the sake of keeping things simple, we create parent classes from which we can extend. The subject and observer parent classes will have those properties and methods required in order to implement the observer pattern.

Here is a basic class diagram for visual reference:

 

Subject Class

The purpose of the subject class is to maintain a list of observers that it needs to notify when it is updated. It will need the ability to add or remove observers as well.

Here is a brief explanation for the properties and methods that are required on the Subject class:

  • observers – This class property holds an array of observers.
  • addObserver() – Will push an observer on to the observer’s array
  • removeObserver() – Will remove an observer from the observer’s array
  • notify() – Will notify all observers that a change has happened

Observer Class

The purpose of the observer class is to implement an update() method that will be called by the subjects notify() method. In our case, the concrete implementation of the update() method will re-render the element.

Example Code

If you’re like me, talking theory is cool, but a concrete example is what really helps me understand what is going on.

I’ve created a very simple app that does two things:

  1. Allows users to be added to a list
  2. Updates a user count indicator when a user is added to the list

The basic flow of the app goes like this: when the new user is submitted via the input, a state change is triggered. Because the state has changed, both the list and user counter are automatically re-rendered because they are observing the state object.

Let’s walk through a few of the key files for further explanation and context.

lib/Subject.js

The subject class is one part of the observable pattern. It’s the object that will notify all of the observers that it has changed in some way.

Take note that we have an observers property plus the addObserver, removeObserver, and notify methods.

View the code on Gist.

lib/Observer.js

The observer class is the second part of the observable pattern. It’s that object that gets notified when something in the subject class has updated.

The implementation for the update function is blank in this class. We will leave the implementation details to the concrete class.

View the code on Gist.

lib/State.js

The state class will be the application state for our app. It extends the subject class, so in turn, it inherits all of the functions on the subject class.

On instantiation, the constructor sets the state to an empty object. The get() method just returns the state. The update() method is a bit more interesting. It will update the state and then run the notify() method passing along the updated state. This allows any observers to have access to the updated state.

View the code on Gist.

components/List.js

In total, we have three components in the app. We’ll just look at the list component because the others are very similar.

The list component extends the observable class. This means that it wants to know when the application state (subject) has changed. Notice how we override the update method with an actual implementation that re-renders the component.

View the code on Gist.

Below is a link to the working demo of the app. Check it out and make magic happen by adding a few users.

Click here for the demo!


Lets talk about implementing a solution like this on your website

Recap

Managing state in JavaScript is something that needs to be done frequently. If you have an app that requires updating several elements on the page when state changes, then using the observer pattern is one way you could make that happen.

Feel free to hit me up in the comments below if you have any questions or comments.

The post How to Use the Observable Pattern in JavaScript appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/02/19/observable-pattern-in-javascript/feed/ 9 19636
Compile JavaScript with Webpack in a WordPress Plugin https://webdevstudios.com/2019/01/15/compile-javascript-with-webpack-in-a-wordpress-plugin/ https://webdevstudios.com/2019/01/15/compile-javascript-with-webpack-in-a-wordpress-plugin/#comments Tue, 15 Jan 2019 17:00:40 +0000 https://webdevstudios.com/?p=19542 The goal of this article is to show you how to configure webpack to watch and compile the JavaScript files in a WordPress plugin. What this article will not cover is how to configure webpack to work with every file type known to the world. Our focus is going to be JavaScript. That’s it. What Read More Compile JavaScript with Webpack in a WordPress Plugin

The post Compile JavaScript with Webpack in a WordPress Plugin appeared first on WebDevStudios.

]]>
The goal of this article is to show you how to configure webpack to watch and compile the JavaScript files in a WordPress plugin. What this article will not cover is how to configure webpack to work with every file type known to the world. Our focus is going to be JavaScript. That’s it.

What is webpack?

According to the webpack website:

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

Now you might be asking yourself, what is a dependency graph? In webpack, there are files specified as entry points. These entry points are at the top of the dependency graph. Any files required or imported from the entry files will be processed and bundled by webpack.

File dependency graph.

Benefits

  • Dependency Management – When concatenating JavaScript files for a WordPress plugin or theme, there is not an efficient way to add in third-party libraries. You can either download and enqueue the minified file or, worse yet, include it as part of the files being concatenating. With webpack in use, we get access to using a package manager like npm!
  • ES6 – Webpack is able to transpile the ES6 code you write down to ES5 code making it compatible for older browsers.
  • Code Structure – I think this is one of the biggest benefits of using webpack. Being able to structure our JavaScript code into modules helps to promote reuse and writing clean code. You will see examples of this in the code later in this blog post.

Webpack Basics

Below are brief explanations of four basic webpack concepts that I think are important when getting started.

Entry

The entry point specifies the location to the file that kicks everything off. It’s basically the starting point of your application.

There are several ways to declare entry points for webpack, but when building a config for a WordPress plugin, I typically like to have two entry points. One is for the admin area and one is for the frontend. By doing this, we can enqueue one compiled bundle for each location.

Output

The output specifies the location for the file or files that have been compiled and are ready for use. Just like the entry point, there are several ways to specify output files.

As I stated above, I prefer having two entry points: one for the backend and one for the frontend. This means we will need to also specify two output locations.

Loaders

Loaders are where a lot of the magic behind webpack happens. In basic terms, loaders have the ability to transform code you’ve written before it is imported or ‘loaded.’

An example of a loader would be the babel-loader which will transpile ES6 code down to ES5.

There are countless loaders out there to choose from. The webpack website has a nice list of some of the most used. You can find that list here.

Plugins

The last important concept I wanted to cover is plugins. You can think of these almost like a plugin you would use in WordPress. They basically add additional functionality to webpack.

For example, I like to use the progress bar webpack plugin which adds a simple progress bar during the build process. Find a nice list of popular webpack plugins here.

Now that you have a little bit of background on webpack and the concepts behind it, let’s get to building out a super-simple WordPress plugin that will use webpack to compile its JavaScript files.

Final Plugin Files

Just a quick heads up that a link to the finished plugin files is provided at the end of this tutorial in case you didn’t want to code along.

Step 1: Create a WordPress Plugin

For this WordPress plugin, we are going to keep things as simple as possible. Let’s not get distracted by the different ways to architect a plugin. We’ll keep it to just one file.

Create a folder inside the plugins folder called wp-webpack-example.

Inside the newly created folder, create a file called wp-webpack-example.php and add the code below to the file.

Feel free to customize the plugin information to your liking.

View the code on Gist.

The code above will enqueue a different script for the admin area as well as the frontend. At this point, you should be able to check out the plugins page in the admin area and see the new plugin listed.

Go ahead and activate it! Not much will happen at this point since we haven’t actually created any of the files we are trying to enqueue.

Step 2: Create a package.json File

From a terminal window, change into the wp-webpack-example folder.

Run npm init and answer the questions you are prompted to answer. If you want to skip over those questions, you can run npm init --yes.

Now that we have a package.json setup, we can install some dependencies.

Step 3: Install Dependencies

First, let’s install webpack and the webpack-cli.

From a terminal, make sure you are in the wp-webpack-example folder and run the following command:

npm install --save-dev webpack webpack-cli

Next, let’s install a couple of Babel dependencies. These will transform ES6 down to ES5 so that it will be readable by older browsers as well as giving us access to some of the newer features of ES6.

From the terminal, run the following command:

npm install --save-dev babel-loader @babel/core @babel/cli @babel/preset-env

Finally, let’s install Lodash so you can see how to use a third-party library.

npm install --save-dev lodash

Step 4: Configuring Babel

Normally, I would create a .babelrc file and place the Babel configuration there, but in this case, since the configuration is so simple, we’ll just put it directly in the package.json we created earlier.

Add the Babel portion to the package.json file you created:

View the code on Gist.

Step 5: Create the webpack Config File

Inside the wp-webpack-example folder, create a new file and name it webpack-config.js.

By default, webpack will look for a configuration file named webpack.config.js. I changed the name up for ours because embedding gists that have a . in the name does not work well.

Copy the annotated code from the embed below.

View the code on Gist.

Step 6: Create the rest of the folder structure.

Create the additional files and folder needed to match the directory structure below:

Here are brief descriptions for each folder:

  • assets/js: holds the compiled JS files
  • src/: holds the source JS files
  • src/admin: source files for the admin area
  • src/front: source files for the frontend
  • src/utils: source files for utility functions

You can think of admin/admin-index.js and front/front-index.js as being the entry points for their respective locations.

As a personal preference, I like to create a components folder that will hold all of the individual modules being used for each entry point. You can feel free to change up the directory structure to fit your needs.

Step 7: Add Test Code

Add the following code to utils-index.js. This file contains simple utility functions that we will share between the admin and frontend code.

View the code on Gist.

Add the following code to the admin-test.js file. Here, we are requiring a single utility function upper and using it to uppercase admin logs.

View the code on Gist.

Add the following code to the front-test.js file. Here, we are requiring both shared functions as well as importing the last function from lodash. Yeah, how cool is that? This is what I mean by easy dependency management.

The getLastArrayElement is just a wrapper function for the last function from lodash. It will return the last element of an array.

View the code on Gist.

Add the following code to admin/admin-index.js.

View the code on Gist.

Add the following code to front/front-index.js. Here, we are using that wrapper function getLastArrayElement that uses the last function from lodash.

View the code on Gist.

Step 8: Create Scripts

Adjust the scripts portion of the package.json file to look like the one below. Notice how we are specifying the config file since we didn’t use the standard naming for it. These scripts can then be run from a terminal window.

View the code on Gist.

The Plugin

Coding along with a tutorial can be tedious, so I’ve included a zip file with all the goods to get started with.

Just follow these simple steps:

  1. Download the plugin zip file here: wp-webpack-example
  2. Install it to your local WordPress installation
  3. In the terminal, change into the plugin folder
  4. Run npm install to install the dependencies
  5. Run npm run watch to watch for file changes, or run npm run build to compile the changed files

Open the browser console and load up the homepage of your WordPress installation. You should see output like this:

Next, browse to the dashboard/admin area, you should see output like this:

Recap

We created a simple WordPress plugin that will enqueue a script file for the admin area and one for the frontend portion of the site.

We then created a simple webpack configuration that consists of two entry points and two output files. We also set up a loader that will transpile down our ES6 into ES5 so it is readable on older browsers.

Finally, we created two scripts in the package.json file. One will watch for file changes and the other will build files.

I would really like to encourage developers to think about how they can start using modern JavaScript techniques in their WordPress plugins. It’s just as much about how you structure the JavaScript as it is writing it.

The post Compile JavaScript with Webpack in a WordPress Plugin appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/01/15/compile-javascript-with-webpack-in-a-wordpress-plugin/feed/ 5 19542