How to build a high-quality PWA Studio extension

How to build a high-quality PWA Studio extension

If you wanted to write your own PWA Studio extension, you would have to take care of a few general things like:

  • base module structure

  • static code analysis

  • tests

If you value your time and the quality of your product, you should take steps to make starting as quick and easy as possible. Today I want to introduce the PWA Studio extension generator.

This tool will help you to build high-quality PWA Studio extensions in no time at all.

In this article, I would like to show you how to build your own PWA Studio extension using this generator.

Let’s do it!

First, we need to set up our local PWA Studio instance.

1$ yarn create @magento/pwa

It would be best if you answered some questions on the console.

Then please generate a unique, secure, custom domain for your new project.

1$ cd <PWA Studio root directory>>
2$ yarn run buildpack create-custom-origin .

Scaffolding extension

For development, I recommend creating a module in the pwa-studio-root/src directory and linking it as symlinks in package.json.

1$ cd src/
2$ yarn create @larsroettig/pwa-extension

Again, you will have to answer a few questions.

Your directory structures should look like this:

Now we need to link our module in the package.json file. Please add this entry as a dependency:

1"@marcinkwiatkowski/account-information": "link:<absolute_path_to_module"

Now we need to install our module and run the PWA Studio instance.

1$ yarn install
2$ yarn run watch

Before we start development, we should do four things:

  • add @magento/venia-ui as a peer dependency

  • add @magento/peregrine as a peer dependency

  • run the yarn install command in our module directory

  • drink coffee, water, or whatever you like

A few words about the extension

Today we will create an account information page where Customers will find the necessary information about themselves.

Requirements

  1. The Page should be visible at the ‘base_url/account-information’ URL

    1. the Page should be visible only for logged-in customers

    2. the Customer’s first name and last name will be displayed on the Page.

  2. A link to the Page should be visible in the customer menu

Adding a new route

Now it’s time to coding!

Defining the route

Thanks to targets, we can add a new route to PWA Studio in an easy way. Please add the following content to the intercept.js file:

1targets.of('@magento/venia-ui').routes.tap(routes => {
2    routes.push({
3        name: 'AccountInformation',
4        pattern: '/account-information',
5        path: require.resolve(
6            '@marcinkwiatkowski/account-information/src/lib/components/AccountInformation/'
7        )
8    });
9    return routes;
10});

As you can see on line 6, we defined the component which will be rendered when the user opens the Page.

Adding AccountInformation component

To start, please create a straightforward React component:

1import React from 'react';
2
3const AccountInformation = () => {
4    return (
5        <div>
6            <h1>Hello world</h1>
7        </div>
8    );
9};
10
11export default AccountInformation;

Remember to add an index.js file, which exports the component.

Adding customer data

We need to have three pieces of information about the Customer:

  1. Is the Customer signed in?

  2. First name

  3. Last name

We are going to create the hook which will use the useUserContext talon. Please create a file at src / lib / talons / AccountInformation / useAccountInformation.js with the following content:

1import { useUserContext } from '@magento/peregrine/lib/context/user';
2
3/**
4 * useAccountInformation hook which provides data for AccountInformation component
5 * @returns {{currentUser: {id, email, firstname, lastname, is_subscribed}, isSignedIn: boolean}}
6 */
7export const useAccountInformation = () => {
8    const [{ currentUser, isSignedIn }] = useUserContext();
9
10    return {
11        currentUser,
12        isSignedIn
13    };
14};

Display information about Customer on the Page

To display the Customer’s information, we have to import the hook and add JSX Markup to the component:

1import React from 'react';
2import { useAccountInformation } from '../../talons/AccountInformation/useAccountInformation';
3
4const AccountInformation = () => {
5    const { currentUser, isSignedIn } = useAccountInformation();
6
7    return (
8        <div>
9            <h1>Account information</h1>
10
11            <ul>
12                <li>
13                    <strong>First name: </strong>
14                    <span>{currentUser.firstname}</span>
15                </li>
16                <li>
17                    <strong>Last name: </strong>
18                    <span>{currentUser.lastname}</span>
19                </li>
20            </ul>
21        </div>
22    );
23};
24
25export default AccountInformation;

Adding styles

The next thing which we do is to add styles for our component. Please create the accountInformation.css file in the component directory:

1.root {
2    display: grid;
3    padding: 2.5rem 3rem;
4    row-gap: 2rem;
5}
6
7.title {
8    justify-self: center;
9    font-family: var(--venia-global-fontFamily-serif);
10    font-weight: var(--venia-global-fontWeight-bold);
11}
12
13.list {
14    justify-self: center;
15    margin: 15px auto;
16    text-align: center;
17}

Then you can import these styles as a module component and use them.

1import React from 'react';
2import { useAccountInformation } from '../../talons/AccountInformation/useAccountInformation';
3import { mergeClasses } from '@magento/venia-ui/lib/classify';
4import defaultClasses from './accountInformation.css';
5
6const AccountInformation = props => {
7    const classes = mergeClasses(defaultClasses, props.classes);
8    const { currentUser, isSignedIn } = useAccountInformation();
9
10    return (
11        <div className={classes.root}>
12            <h1 className={classes.title}>Account information</h1>
13
14            <ul className={classes.list}>
15                <li>
16                    <strong>First name: </strong>
17                    <span>{currentUser.firstname}</span>
18                </li>
19                <li>
20                    <strong>Last name: </strong>
21                    <span>{currentUser.lastname}</span>
22                </li>
23            </ul>
24        </div>
25    );
26};
27
28export default AccountInformation;

Checking if the Customer is logged in

We want to redirect to the homepage when the Customer is not logged in. To achieve this, we are going to use the @magento/venia-drivers Redirect component.

1import React from 'react';
2import { useAccountInformation } from '../../talons/AccountInformation/useAccountInformation';
3import { Redirect } from '@magento/venia-ui/lib/drivers';
4import { mergeClasses } from '@magento/venia-ui/lib/classify';
5import defaultClasses from './accountInformation.css';
6
7const AccountInformation = props => {
8    const classes = mergeClasses(defaultClasses, props.classes);
9    const { currentUser, isSignedIn } = useAccountInformation();
10
11    if (!isSignedIn) {
12        return <Redirect to="/" />;
13    }
14
15    return (
16        <div className={classes.root}>
17            <h1 className={classes.title}>Account information</h1>
18
19            <ul className={classes.list}>
20                <li>
21                    <strong>First name: </strong>
22                    <span>{currentUser.firstname}</span>
23                </li>
24                <li>
25                    <strong>Last name: </strong>
26                    <span>{currentUser.lastname}</span>
27                </li>
28            </ul>
29        </div>
30    );
31};
32
33export default AccountInformation;

Our Page should look like this now:

Adding a link to the customer menu

The Page looks good, but Customers need to know that this Page exists, so we will add a \ link to the customer menu. If the user clicks the link, PWA Studio will redirect to the account-information Page.

Note: I’m using overwrites here to extend the VeniaUI component and overwrite talon, but in the next version of PWA Studio, there will be a better way to extend talons using a new called Targetables.

We will use WebpackNormalOverridePlugin to add overwrites. If you are not familiar with this technique, please check one of my recent articles.

Overwriting components

Create the file lib / components / AccountMenu / accountMenuItems.js

1import React from 'react';
2import { func, shape, string } from 'prop-types';
3import { FormattedMessage } from 'react-intl';
4
5import { Link } from '@magento/venia-drivers';
6import { mergeClasses } from '@magento/venia-ui/lib/classify';
7import { useAccountMenuItems } from '../../talons/AccountMenu/useAccountMenuItems';
8
9import defaultClasses from '@magento/venia-ui/lib/components/AccountMenu/accountMenuItems.css';
10
11const AccountMenuItems = props => {
12  const { onSignOut } = props;
13
14  const talonProps = useAccountMenuItems({ onSignOut });
15  const { handleSignOut, menuItems } = talonProps;
16
17  const classes = mergeClasses(defaultClasses, props.classes);
18
19  const menu = menuItems.map(item => {
20    return (
21      <Link className={classes.link} key={item.name} to={item.url}>
22        <FormattedMessage id={item.id} />
23      </Link>
24    );
25  });
26
27  return (
28    <div className={classes.root}>
29      {menu}
30      <button className={classes.signOut} onClick={handleSignOut} type="button">
31        <FormattedMessage id={`Sign Out`} />
32      </button>
33    </div>
34  );
35};
36
37export default AccountMenuItems;
38
39AccountMenuItems.propTypes = {
40  classes: shape({
41    link: string,
42    signOut: string
43  }),
44  onSignOut: func
45};

The most important thing here is line 7 where we change the path to the useAccountMenuItems talons.

The next thing we need is the lib / talons / AccountInformation / useAccountInformation.js talon.

1import { useCallback } from 'react';
2
3/**
4 * @param {Object}      props
5 * @param {Function}    props.onSignOut - A function to call when sign out occurs.
6 *
7 * @returns {Object}    result
8 * @returns {Function}  result.handleSignOut - The function to handle sign out actions.
9 */
10export const useAccountMenuItems = props => {
11  const { onSignOut } = props;
12
13  const handleSignOut = useCallback(() => {
14    onSignOut();
15  }, [onSignOut]);
16
17  const MENU_ITEMS = [
18    {
19      name: 'Communications',
20      id: 'accountMenu.communicationsLink',
21      url: '/communications'
22    },
23    {
24      name: 'Account Information',
25      id: 'accountMenu.accountInfoLink',
26      url: '/account-information'
27    }
28  ];
29
30  return {
31    handleSignOut,
32    menuItems: MENU_ITEMS
33  };
34};

The last thing is to add moduleOverrideebpackPlugin, add a mapping, and modify the intercept.js file.

I’ll let you handle this one!

If you do it correctly, you will see a link to the Page in the menu:

Unit tests

Thanks to the generator, we have already configured the environment for unit tests. We can use the Jest Testing Framework.

Please add a src / lib / components / AccountInformation / __tests__/ AccountInformation.spec.js file with the following content:

1import React from 'react';
2import { default as createTestInstance } from '@magento/peregrine/lib/util/createTestInstance';
3import { useAccountInformation } from '../../../talons/AccountInformation/useAccountInformation';
4import AccountInformation from '../AccountInformation';
5
6jest.mock(
7    '@marcinkwiatkowski/customer-menu/src/lib/talons/AccountInformation/useAccountInformation'
8);
9jest.mock('@magento/venia-ui/lib/classify');
10jest.mock('@magento/peregrine/lib/context/user', () => {
11    const userState = {
12        isGettingDetails: false,
13        getDetailsError: null
14    };
15    const userApi = {
16        getUserDetails: jest.fn(),
17        setToken: jest.fn(),
18        signIn: jest.fn()
19    };
20    const useUserContext = jest.fn(() => [userState, userApi]);
21
22    return { useUserContext };
23});
24
25jest.mock('@magento/venia-ui/lib/drivers', () => ({
26    Redirect: props => <mock-Redirect {...props} />
27}));
28
29test('Redirects when not authenticated', () => {
30    useAccountInformation.mockReturnValue({
31        isSignedIn: false,
32        currentUser: null
33    });
34
35    const tree = createTestInstance(<AccountInformation />);
36    expect(tree.toJSON()).toMatchSnapshot();
37});
38
39test('Display page when user is signed in', () => {
40    useAccountInformation.mockReturnValue({
41        isSignedIn: true,
42        currentUser: {
43            firstname: 'Marcin',
44            lastname: 'Kwiatkowski'
45        }
46    });
47
48    const tree = createTestInstance(<AccountInformation />);
49    expect(tree.toJSON()).toMatchSnapshot();
50});

Running tests

If you want to run a test, just run this command:

1$ yarn run test

The results should look like this:

Other generator features

The generator has a few other features which help you to create excellent quality components.

Linting

ESLint checks all JavaScript code. You can run this linter manually using this command:

1$ yarn run lint

Configuration for esLint is in the .eslintrc.js file.

Code formatting

Also, you can automatically format your code by running this command:

1$ yarn run format

Husky

Thanks to Husky, these commands (lint and format) run automatically before each git commit.

Source code

You can find the source code of the extension which we just made on my Github.

Summary

As you can see, thanks to PWA Studio Extension Generator, you can start developing your extension quickly, and you don’t have to worry about configuring things from scratch. You can grab base files and configs and change whatever you want. Happy Hacking!

About the author

Marcin Kwiatkowski

Frontend developer, Certified Magento Full Stack Developer, writer, based in Poland. He has eight years of professional Software engineering experience. Privately, husband and father. He likes reading books, drawing, and walking through mountains.

Read more