# Create ScandiPWA App

Set up a ScandiPWA store-front by running one command.

### Less to learn

You don't need to learn and configure many build tools. Instant reloads help you focus on development. When it's time to deploy, your bundles are optimized automatically.

### Only One Dependency

Your app only needs one build dependency. We test Create ScandiPWA App to make sure that all of its underlying pieces work together seamlessly – no complicated version mismatches.

## 🚀 Get started in seconds

Create ScandiPWA App allows you to **focus on code, not build tools**.\
\
To create a project called `my-app`, run this command:

```bash
npx create-scandipwa-app my-app
```

{% content-ref url="/pages/-MKo2b5QXiLobVBS14FI" %}
[Getting Started](https://docs.create-scandipwa-app.com/getting-started/getting-started)
{% endcontent-ref %}

## 🛠 Easy to Maintain

Updating your build tooling is typically a daunting and time-consuming task. When new versions of Create React App are released, you can upgrade using a single command:

```bash
npm install @scandipwa/scandipwa-scripts@latest
```

{% content-ref url="/pages/-MKp6N56x89PYiz8lpOe" %}
[Updating to New Releases](https://docs.create-scandipwa-app.com/getting-started/updating-to-new-releases)
{% endcontent-ref %}


# Getting Started

Create ScandiPWA App is the recommended way to create ScandiPWA applications. It offers a modern build setup with no configuration.

## Summary

* [ ] Ensure you have Node v14 (npm v6) on your development machine
* [ ] `npx create-scandipwa-app my-app` to create a new app
* [ ] `cd my-app` to enter your app's directory
* [ ] `npm start` to run the app

These commands will create a new Scandi app, start it up, and open it in your browser.

## Creating an App

**You’ll need to have Node v14 on your local development machine** (but it’s not required on the server). You can use [n](https://www.npmjs.com/package/n) (macOS, Linux) or [nvm-windows](https://github.com/coreybutler/nvm-windows#node-version-manager-nvm-for-windows) to switch Node versions between different projects.

You **don’t** need to install or configure tools like Webpack or Babel. They are preconfigured and hidden so that you can focus on the code.

To create a new app, use `create-scandipwa-app`:

### NPX

{% tabs %}
{% tab title="npx" %}

```bash
npx create-scandipwa-app my-app
```

{% endtab %}

{% tab title="npm" %}

```
npm init scandipwa-app my-app
```

{% endtab %}

{% tab title="yarn" %}

```
yarn create scandipwa-app my-app
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
To create an empty template instead of the default Scandi theme, use the `--template blank` option.
{% endhint %}

## Expected Output

Running these commands will create a directory called `my-app` inside the current folder. Inside that directory, it will generate the initial project structure and install the transitive dependencies:

```bash
📁  my-app
├── 📄  README.md
├── 📄  composer.json
├── 📁  i18n
├── 📁  magento
|  ├── 📁  etc
|  |  └── 📄  view.xml
|  ├── 📄  registration.php
|  └── 📄  theme.xml
├── 📁  node_modules
├── 📄  package.json
├── 📁  public
├── 📁  src
└── 📄  yarn.lock
```

No configuration or complicated folder structures, only the files you need to build your ScandiPWA app.

## Scripts

Inside the newly created project, you can run some built-in commands:

### `npm start` or `yarn start`

Runs the app in development mode. Will open the [http://localhost:3000](http://localhost:3000/) to preview changes in your default browser.\
\
The page will automatically reload if you make changes to the code. You will see the build errors and lint warnings in the console.

### `npm run build` or `yarn build`

Builds the app for production to the `build` folder. It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.

Your app is ready to be deployed.

### Linking the theme

If you are installing the ScandiPWA theme on a CMA setup, after you build it you should also link your theme to your Create Magento App project:

[Click here for instructions](https://docs.create-magento-app.com/usage-guide/themes).


# Folder structure

After creation, your project should look like this:

```bash
├── 📁  i18n
├── 📁  magento
|  ├── 📁  etc
|  |  └── 📄  view.xml
|  ├── 📄  registration.php
|  └── 📄  theme.xml
├── 📁  node_modules
├── 📄  package.json
├── 📁  public
├── 📁  src
└── 📄  yarn.lock
```

As you may have noticed, the `src` and `public` folders are empty. Why so?

{% hint style="info" %}
**The application you just created is a ScandiPWA theme**.\
\
It uses parent-theme files to compile. Your theme's `src` and `public` folders are empty, therefore each file is referenced from a parent theme.\
\
Your application's parent theme is `@scandipwa/scandipwa`. It is located in `node_modules/@scandipwa/scandipwa`folder.
{% endhint %}

## Important files and folders

Any ScandiPWA application must include following files:

| File name           | Intended purpose           |
| ------------------- | -------------------------- |
| `src/index.js`      | The JavaScript entry point |
| `public/index.html` | The page template          |

{% hint style="info" %}
These files might be defined in your theme, parent theme, or provisioned by extensions.
{% endhint %}

In case of your project, the `src/index.js` and `public/index.html` are located in your parent theme. You may however create these files in your theme, then, they will be preferences over the parent theme defined files.

You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack. You need to **put all JS and CSS files inside `src`** folder, otherwise Webpack won’t see them.

You can, however, create more top-level directories. They will not be included in the production build so you can use them for things like documentation.

There are some ScandiPWA extensions, which might define new required files. In example, there is an extension`@scandipwa/m2-theme` which allows to compile into Magento 2 theme. It defines a new PHP page template:

| File name       | Intended purpose                            |
| --------------- | ------------------------------------------- |
| `src/index.php` | The Magento 2 theme's `root.phtml` template |

You may  re-define this template in your theme. However, by default the `src/index.php` will be provided by `@scandipwa/m2-theme` extension.

## Working with files

ScandiPWA introduces the concept of "overriding" files.

{% hint style="info" %}
**To override a file** - means to create a file which will be used instead of some other file. You can override files of any extension or parent theme.
{% endhint %}

You can learn more about overriding in the [File overrides](https://docs.create-scandipwa-app.com/themes/parent-themes) section.


# Supported Browsers & Features

By default, the generated project supports all modern browsers. Support for Internet Explorer 9, 10, and 11 requires polyfills. For a set of polyfills to support older browsers, use [react-app-polyfill](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md).&#x20;

{% hint style="danger" %}

### Watch out!

Some themes, for example, the`@scandipwa/scandipwa`**does not support Internet Explorer at all**. Therefore, if your parent theme is `@scandipwa/scandipwa,`you won't be able to enjoy ScandiPWA in the Internet Explorer.
{% endhint %}

## Supported Language Features

This project supports a superset of the latest JavaScript standard. In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:

* [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
* [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
* [Object Rest/Spread Properties](https://github.com/tc39/proposal-object-rest-spread) (ES2018).
* [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 4 proposal)
* [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
* [JSX](https://facebook.github.io/react/docs/introducing-jsx.html), [Flow](https://create-react-app.dev/docs/adding-flow) and [TypeScript](https://create-react-app.dev/docs/adding-typescript).

Learn more about [different proposal stages](https://tc39.github.io/process-document/).

While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.

Note that **this project includes no** [**polyfills**](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md) by default.

If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are [including the appropriate polyfills manually](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md), or that the browsers you are targeting already support them.

## Supported Styling Options

This project also supports:

* CSS
* [PostCSS](https://postcss.org/) ([Autoprefixer](https://github.com/csstools/postcss-preset-env))
* [SASS](https://sass-lang.com/)

Support for new CSS features like the [`all` property](https://developer.mozilla.org/en-US/docs/Web/CSS/all), [`break` properties](https://www.w3.org/TR/css-break-3/#breaking-controls), [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables), and [media query ranges](https://www.w3.org/TR/mediaqueries-4/#range-context) are automatically poly-filled to add support for older browsers.

{% hint style="info" %}
[CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) prefixing is disabled by default, but it will **not** strip manual prefixing. If you'd like to opt-in to CSS Grid prefixing, [first familiarize yourself about its limitations](https://github.com/postcss/autoprefixer#does-autoprefixer-polyfill-grid-layout-for-ie).

To enable CSS Grid prefixing, add `/* autoprefixer grid: autoplace */` to the top of your CSS file.
{% endhint %}

## Configuring Supported Browsers

By default, the generated project includes a [`browserslist`](https://github.com/browserslist/browserslist) configuration in your `package.json` file to target a broad range of browsers based on global usage (`> 0.2%`) for production builds, and modern browsers for development. This gives a good development experience, especially when using language features such as async/await, but still provides high compatibility with many browsers in production.

The `browserslist` configuration controls the output JavaScript so that the emitted code is compatible with the browsers specified. The `production` list will be used when creating a production build by running the `build` script, and the `development` list will be used when running the `start` script. You can use [https://browserl.ist](https://browserl.ist/?q=%3E+0.2%25%2C+not+dead%2C+not+op_mini+all) to see the browsers supported by your configured `browserslist`.

Here is an example `browserslist` that is specified in `package.json`:

```javascript
"browserslist": {
  "production": [
    ">0.2%",
    "not dead",
    "not op_mini all"
  ],
  "development": [
    "last 1 chrome version",
    "last 1 firefox version",
    "last 1 safari version"
  ]
}
```

{% hint style="danger" %}

### Watch out!

The `browserlist` does not include polyfills automatically for you. You will still need to polyfill language features (see above) as needed based on the browsers you are supporting.
{% endhint %}

## Missing a feature?

This project allows you to create extensions to its own build configuration. You can always add a missing feature to your project by following the build extension guide.


# Updating to New Releases

Create ScandiPWA App is divided into two packages:

* `create-scandipwa-app` is a global command-line utility that you use to create new projects.
* `@scandipwa/scandipwa-scripts` is a development dependency in the generated projects (including this one).

When you run `npx create-scandipwa-app my-app` it automatically installs the latest version of Create React App.

Create React App creates a project with the latest version of `@scandipwa/scandipwa-scripts` so you’ll get all the new features and improvements in newly created apps automatically.

To update an existing project to a new version of `@scandipwa/scandipwa-scripts`, [open the change-log](https://github.com/scandipwa/create-scandipwa-app/releases), find the version you’re currently on (check `package.json` in this folder, if you’re not sure), and apply the migration instructions for the newer versions.

In most cases bumping the `@scandipwa/scandipwa-scripts` version in `package.json` and running `npm install` (or `yarn install`) in this folder should be enough, but it’s good to consult the [change-log](https://github.com/scandipwa/create-scandipwa-app/releases) for potential breaking changes.

To bump the version of `@scandipwa/scandipwa-scripts` to latest available version, use:

{% tabs %}
{% tab title="yarn (recommended)" %}

```
yarn add @scandipwa/scandipwa-scripts@latest
```

{% endtab %}

{% tab title="npm" %}

```
npm install @scandipwa/scandipwa-scripts@latest
```

{% endtab %}
{% endtabs %}

We commit to keeping the breaking changes minimal so you can upgrade `@scandipwa/scandipwa-scripts` painlessly.


# Themes

The project introduces the concept of "themes".

{% hint style="info" %}
**Theme** - is a collection of components, which implements a presentation layer that is unique to your application. It should not contain any business logic. It should simply adopt extensions functionality to intended design of your application.
{% endhint %}

For application to be considered a theme, it must have a `package.json` field `scandipwa.type` equal to `theme`. For example:

```javascript
{
    "scandipwa": {
        "type": "theme"
    }
    ...
}
```

The theme is what you compile into running website, therefore it also contains `start` and `build` scripts. You can read more about them in the "[Getting started](https://docs.create-scandipwa-app.com/getting-started/getting-started#scripts)" section.

## Parent theme

Themes can stack on top of each another. A theme which another theme is based on is called a **parent theme**. To specify a parent theme, set the `package.json` field `scandipwa.parentTheme` equal to intended parent theme package name.

{% hint style="warning" %}
If you are selecting a new parent theme, it is not enough to just set the value of `scandipwa.parentTheme`in `package.json`. The parent theme package should be listed among of your package `dependencies`.
{% endhint %}

The properly installed parent theme `package.json` could look like this:

```javascript
{
    "dependencies": {
        "@scandipwa/scandipwa": "1.0.1",
        ...
    },
    "scandipwa": {
        "type": "theme",
        "parentTheme": "@scandipwa/scandipwa",
        ...
    },
    ...
}
```

A theme can override files of a parent theme. Learn more about overriding a parent theme in the [File overrides](https://docs.create-scandipwa-app.com/themes/parent-themes#to-override-a-file-of-a-parent-theme) guide.

## Theme Webpack alias

In previous versions of ScandiPWA, the import from parent theme looked the following way:

```javascript
import { AddToCart } from 'SourceComponent/AddToCart/AddToCart.component';
```

You may have noticed the `SourceComponent` alias appearing in the begging of the import. This allows to define shorter import paths. This alias is composed from a folder inside of the `src` and the prefix of the theme. The `@scandipwa/scandipwa` theme has a prefix `Source` . The `src` folders which support this mapping are:

| Folder alias | Path from theme root | Purpose                     |
| ------------ | -------------------- | --------------------------- |
| Style        | `./src/style`        | Global styles               |
| Component    | `./src/component`    | React component definitions |
| Route        | `./src/route`        | Router pages definitions    |
| Util         | `./src/util`         | Utility functions           |
| Query        | `./src/query`        | GraphQL query definitions   |
| Type         | `./src/type`         | React prop-type definitions |
| Store        | `./src/store`        | Redux store definitions     |

To define a Webpack alias for your theme, you are required to define the `scandipwa.themeAlias` field in `package.json`. The value you define in this field will be used as your theme prefix. You can do it like this:

```javascript
{
    "scandipwa": {
        "type": "theme",
        "themeAlias": "Source",
        ...
    }
    ...
}
```

{% hint style="info" %}
Setting the Webpack alias for a theme which is not used as a parent is not required. This field **only** comes into play, when a theme is selected as a parent theme for another one.
{% endhint %}

There is however, another way to import files from a parent theme. You can always import the file from the NPM package of your parent theme directly. Like so:

```javascript
import { AddToCart } from '@scandipwa/scandipwa/src/component/AddToCart/AddToCart.component'; 
```

Both of these approaches are valid, but for consistency, we recommend using Webpack aliases.


# File overrides

ScandiPWA introduces the concept of "overriding" files. **Overrides are a feature of** [**ScandiPWA themes**](https://docs.create-scandipwa-app.com/themes/extensions-and-themes).

{% hint style="info" %}
**To override a file** - means to create a file which will be used instead of some other file. You can override files of any extension or parent theme.
{% endhint %}

## To override a file of a parent theme

{% tabs %}
{% tab title="Instruction" %}

1. Determine your parent theme location:
   1. Locate `package.json` in your theme and pay attention to field `scandipwa.parentTheme`
   2. Navigate to `node_modules/<PARENT THEME NAME>`
2. Locate the file you intend to override in a parent theme folder
3. Create a new file in your theme, which:
   1. Has the same name as the original file
   2. Is located in the same folder (relative to `src`) as the original file

{% hint style="warning" %}
In case the `package.json`field`scandipwa.parentTheme`is empty, your theme is considered to be a **root theme**. In this case, parent theme overrides will not function, as there is simply no parent theme.
{% endhint %}
{% endtab %}

{% tab title="Example" %}
To override a file `AddToCart.component.js`:

1. Check our theme's `package.json` file:
   1. The value of `scandipwa.parentTheme` is `@scandipwa/scandipwa`&#x20;
   2. The location of a parent theme therefore is `node_module/@scandipwa/scandipwa` &#x20;
2. Search for `AddToCart.component.js` in a **parent theme files**:
   1. The file was found in `src/component/AddToCart/AddToCart.component.js`
3. Create a new file in our theme:
   1. Filename is `AddToCart.component.js`
   2. Folder it should be located in is `src/component/AddToCart`
      {% endtab %}
      {% endtabs %}

## To override an extension file

{% tabs %}
{% tab title="Instruction" %}

1. Determine an extension the file you intend to override belongs to
   1. Run a theme using the `start` script
   2. Use the browser's developer console to search for a filename
2. Locate the file you intend to override in the extension
3. Create a new folder in your theme's `src` folder, which matches the extension name
   1. You can find the extension name in the `name` field of the extension's `package.json`
4. Create a new file in your theme, which:
   1. Has the same name as the original file
   2. Is located in the same folder (relative to `src`) as the original file, but under the newly created extension specific folde&#x72;**.** The pattern for the folder to create extension in is `src/<EXTENSION NAME>/<PATH AS IS EXTENSION>`.

{% hint style="info" %}
Extension might also [provision a path](https://docs.create-scandipwa-app.com/extensions/extensions#extension-file-provision). In example, the `@scandipwa/m2-theme` provision the `public/index.php` file. To override this file, you need to create the exact path in your application theme, without creating the folder matching extension name.
{% endhint %}
{% endtab %}

{% tab title="Example" %}
To override a file `PayPal.component.js`:

1. Using the Google Chrome, search for the `PayPal.component.js`
   1. The search results point us to `node_modules/@scandipwa/pay-pal/src/component/PayPal/PayPal.component.js`
   2. The extension, therefore is `@scandipwa/pay-pal`&#x20;
   3. And the file is located in `src/component/PayPal/PayPal.component.js`
2. Create a new folder matching the extension name: `src/@scandipwa/pay-pal`
3. Create a new file in our theme:
   1. Filename is `PayPal.component.js`
   2. Folder it should be located in is `src/@scandipwa/pay-pal/component/PayPal`
      {% endtab %}
      {% endtabs %}

The "overrides", however, are optional. You can freely create folders and files in ScandiPWA folder. The override-mechanism **will only function for files in the** `src` **and** `public` **folders** your theme, parent theme or extensions.

{% hint style="danger" %}

### **Watch-out!**

If the file you created will unintentionally match extension's or parent theme's path, it will override it. Be careful not to break the functionality, while creating new files and folders.
{% endhint %}

## The sequence of preference

ScandiPWA implements following sequence of override preference (from highest priority to lowest):

1. Your theme files
2. Your theme's parent themes files
3. Extensions files

{% hint style="warning" %}
An extension can not **override** another extension's file. This feature is only available for themes.
{% endhint %}


# Extensions

The project introduces the concept of "extensions".

{% hint style="info" %}
**Extension** - is a reusable, isolated part of your application. It can contain presentation layer, business logic or even build configuration.
{% endhint %}

For NPM package to be considered an extension, it must have a `package.json` field `scandipwa.type` equal to `extension`. For example:

```javascript
{
    "scandipwa": {
        "type": "extension"
    }
    ...
}
```

The **extensions are power-less without a theme**. The application compiles from a theme sources. Extensions are just an isolated pieces, which make some features of your application work.

{% hint style="info" %}
Any package containing the `@namespace` magic comments **must** have a `scandipwa` block declared in its package.json file. Otherwise, the `@namespace` magic comments will not be handled correctly during the build time, hence will not work.
{% endhint %}

## Registering an extension

**Both themes and extensions can register extensions**. In order to do it, the extension should be added to `scandipwa.extensions` object of `package.json` . The extension must be a valid NPM package, therefore you are required to add it into `dependencies` field of your `package.json`. Like so:

```javascript
{
    "dependencies": {
        "@scandipwa/m2-theme": "0.0.2",
        ...
    },
    "scandipwa": {
        "extensions": {
            "@scandipwa/m2-theme": true
        },
        ...
    }
    ...
}
```

This process could be automated using [ScandiPWA CLI](https://docs.scandipwa.com/developing-with-scandi/developer-tools/scandipwa-cli). First, make sure you are in your theme's root folder. Now, to install an extension from NPM registry, you can use following command:

```javascript
scandipwa extension install <PACKAGE>
```

In order to create new extension, use following command:

```javascript
scandipwa extension create <PACKAGE>
```

{% hint style="info" %}
This command will create a new extension in the `packages` folder and register it in your current theme. It will be symlinked from `packages` to proper folder under `node_modules`.
{% endhint %}

## Enabling an extension

Enabling and disabling an extension is achieved by setting the `true`or `false` as a value of the extension key in `scandipwa.extensions` . Your theme can control enabled extensions across the whole application. This allows to disable the previously enabled extension. The sequence of preference in this case is:

1. Your theme enabled extensions
2. Your theme's parent themes enabled extensions
3. Extension enabled extensions

{% hint style="danger" %}

### Watch out!

Disabling a previously enabled extension can lead to layout-shifts and issues inside of your parent theme. Also, there might be extensions plugging into the extension you intend to disable, this can lead to unexpected results.
{% endhint %}

## Extension features

Extensions are very important and powerful part of ScandiPWA tool-chain. Following feature are available:

* [Application plugins](https://docs.create-scandipwa-app.com/extensions/application-plugins)
* [Build configuration plugins](https://docs.create-scandipwa-app.com/extensions/build-configuration-plugins)
* [Module preference](https://docs.create-scandipwa-app.com/extensions/virtual-modules)
* [File provision](https://docs.create-scandipwa-app.com/extensions/file-provision)

Following features are upcoming in next versions of Create ScandiPWA App releases:

* Translation bundles
* HTML template plugin

##


# Installation

Learn how to install ScandiPWA extensions both from remote registry and from local modules

## Overview

The `create-scandipwa-app` setup considers having BE and FE of your application completely separated.

When you purchase an extension, you get access to all of its parts - both BE and FE. The BE part should be handled just as any other installable module for BE of your choice (e.g. Magento 2).

The frontend part of an extension is a regular node module with structure and contents dictated by the `create-scandipwa-app` plugin system.

## Install from a local source

1. Download the archive containing the FE part of the extension from the marketplace.
2. Create a `packages/` directory inside of your theme's root.
3. Put the archive's contents inside of the `packages/<package name>` directory. Make sure that you have a `packages/<package name>/package.json` file present alongside all the other extension's contents, that means that you have unpacked the extension correctly. Note: `<package name>` can also include publisher, `@scandipwa/paypal` is a valid package name.
4. Add the following scripts to the `scripts` section of your theme's `package.json` file. This is necessary for your package to be symlinked into the `node_modules` directory of your theme after manipulations with dependencies

   ```javascript
   {
       "scripts": {
           "postinstall": "scandipwa-scripts link",
           "postupdate": "scandipwa-scripts link"
       }
   }
   ```
5. Add the extension to the dependencies of your theme, as follows:

   ```javascript
   {
       "dependencies": {
           "<package name>": "file:packages/<package name>"
       }
   }
   ```
6. Update the symlinks by running the following command

   ```bash
   # For yarn users
   yarn postinstall

   # For npm users
   npm run postinstall
   ```
7. [Enable the extension](https://docs.create-scandipwa-app.com/extensions/installation#enable-the-extension)

## Install with a package manager (beta)

Some of the FE ScandiPWA extensions are available for installation using `npm` and `yarn`.

The process is a different from the regular module's installation, the ScandiPWA packages are stored in our own registry - `r.scandipwa.com`

The installation process is the following:

1. Get the [credentials](https://marketplace.scandipwa.com/scandipwa_npmregistry/index/auth/) (token) from the [marketplace](https://marketplace.scandipwa.com/)
2. Configure the token for your project

   2.1. Create an `.npmrc` file inside of your project's root directory, neighboring to the `package.json` file. The `.npmrc` file should be created even if you are using `yarn`.

   2.2. Put your token in there in the following format:

   ```bash
   TOKEN=put.token.here
   //r.scandipwa.com/:_authToken=$TOKEN
   ```
3. Add the desired package to your project's dependencies (and fetch it)

   ```bash
   # Write a full command
   yarn --registry https://r.scandipwa.com add <package>
   npm --registry https://r.scandipwa.com i <package>

   # Or create an alias
   alias yr='yarn --registry https://r.scandipwa.com'
   alias npr='npm --registry https://r.scandipwa.com'

   # and use it
   yr add <package>
   npr i <package>
   ```
4. When installing your project's dependencies, don't worry about any additional actions. The `yarn.lock` or `package-lock.json` will contain all the necessary data

   ```bash
   # For yarn users
   yarn

   # For npm users
   npm ci
   ```
5. [Enable the extension](https://docs.create-scandipwa-app.com/extensions/installation#enable-the-extension)

## Enable the extension

Turn on the extension in your theme's `package.json` file. You may turn it off by changing `true` to `false` in the corresponding `extensions` block's entry.

```javascript
    {
        "scandipwa": {
            "extensions": {
                "<package name>": true
            }
        }
    }
```

## Install by using `scandipwa-cli`

Currently, it is possible to install the extensions published to `npm` with the `scandipwa-cli` package, by using `scandipwa extension install` command.

It is planned to provide support for installing local extensions in the future.

More information about installing via `scandipwa-cli` from `npm` registry see [here](https://docs.create-scandipwa-app.com/extensions/extensions).


# Application plugins

ScandiPWA introduces the concept of "plugins". **This is a feature of** [**ScandiPWA extensions**](https://docs.create-scandipwa-app.com/extensions/extensions).&#x20;

{% hint style="info" %}
**To create a plugin** - means to create a programmable proxy between original function and the function caller. Plugin can modify original function arguments and return value.
{% endhint %}

## To create a plugin for class

{% tabs %}
{% tab title="Instruction" %}

1. Understand which class member you would like to proxy. Retrieve this class namespace by looking at it's leading comments.
2. Define the [type of class proxy](https://docs.create-scandipwa-app.com/extensions/application-plugins#you-are-now-able-to-proxy-these-object-types) you would like to implement. If is is:
   * `member-function`, `member-properties`, `static-member` it requires an additional configuration object with method or a property name mapped to the proxy implementation.
   * `class` it expects the proxy implementation without any configuration objects.
3. Create a new plugin file following [these guidelines](https://docs.create-scandipwa-app.com/extensions/application-plugins#file-structure).
4. In this file, `export default` the[ plugin options](https://docs.create-scandipwa-app.com/extensions/application-plugins#plugin-configuration-syntax):
   1. Use namespace you obtained at the step 1).
   2. Use the plugin type you defined at the step 2).
   3. Pay attention to configuration option of your desired plugin type.
5. Take a look[ at the reference](https://docs.create-scandipwa-app.com/extensions/application-plugins#proxy-function-implementation-types) and define a proxy implementation based on your proxy type. Make sure you are passing in the correct arguments.
6. Implement the proxy function according to your intention.

{% hint style="info" %}
You can create class members that do not exist in the original classes. It is useful when you need some life-cycle member functions that are not present in the original class.&#x20;

**Remember** to call the`callback` even if the original member is not present, that will make your plugin compatible with other plugins around the same member, by calling them after your plugin finishes its work.
{% endhint %}
{% endtab %}

{% tab title="Example" %}
The main purpose of this plugin is to inject additional fields `base_grand_total` and `base_currency_code` into the `Cart.query.js` file's class method `_getCartTotalsFields` return value.

1. The class `CartQuery` declared in `Cart.query.js` is bind to a namespace `Query/Cart`.
2. We plan on modifying the class method, therefore we use `member-function` proxy type. It is special and requires a configuration object. It requires a method name as a key.
3. Create a new file `CartQuery.plugin.js` in `src/plugin`, pay attention to `plugin` post-fix.
4. Define an `export default` object:
   1. Use our namespace key from the step 1) - `Query/Cart`.
   2. Use the plugin type from step 2) - `member-function`.
   3. As stated in 2) the method we intend to modify is `_getCartTotalsFields` therefore we declare it in the `member-function` configuration object.
5. Proxy implementation function of `member-function` type takes following arguments: `args`, `callback` and `instance`. We do not need to call any other methods of the `CartQuery` class instance, therefore, we can omit the last argument.
6. Call the original method passing in the original arguments to get the original return value. This is done by calling `callback(...args)`. Then, we extend the original return value with two additional fields: `base_grand_total` and `base_currency_code`.

```javascript
const addBaseFields = (args, callback) => {
    return [
        ...callback(...args),
        'base_grand_total',
        'base_currency_code'
    ];
};

export default {
    'Query/Cart': {
        'member-function': {
            _getCartTotalsFields: addBaseFields
        }
    }
};
```

{% endtab %}
{% endtabs %}

## To create a plugin for a function

{% tabs %}
{% tab title="Instruction" %}

1. Understand which function you would like to proxy. Retrieve this function namespace by looking at it's leading comments.
2. Define the [type of class proxy](https://docs.create-scandipwa-app.com/extensions/application-plugins#you-are-now-able-to-proxy-these-object-types) you would like to implement. In this case it is `function`.
3. Create a new plugin file following [this guidelines](https://docs.create-scandipwa-app.com/extensions/application-plugins#file-structure).
4. In this file, `export default` the[ plugin options](https://docs.create-scandipwa-app.com/extensions/application-plugins#plugin-configuration-syntax):
   1. Use namespace you obtained at the step 1).
   2. Use the plugin type you defined at the step 2).
5. Take a look[ at the reference](https://docs.create-scandipwa-app.com/extensions/application-plugins#proxy-function-types) and define a proxy implementation based on your proxy type. Make sure you are passing in the correct arguments.
6. Implement the proxy function according to your intention.
   {% endtab %}

{% tab title="Example" %}
The main purpose of this plugin is to inject a new field `gtm` into the file's `Config.reducer.js` reducer `ConfigReducer` initial state. We know, that the function `getInitialState` is responsible for that.

1. The function `getInitialState` declared in `Config.reducer.js` is bind to a namespace `Store/Config/Reducer/getInitialState`.
2. We plan on modifying the function assignment, therefore we use `function` proxy type.
3. Create a new file `ConfigStore.plugin.js` in `src/plugin`, pay attention to plugin post-fix.
4. Define an `export default` object:
   1. Use our namespace key from the step 1) - `Store/Config/Reducer/getInitialState`.
   2. Use the plugin type from step 2) - `function`.
5. Proxy implementation function of `function` type takes following arguments: `args`, `callback` and `context`. We have no intention to interact with that function context, therefore, we can omit the last argument.
6. Call the original method passing in the original arguments to get the original return value. This is done by calling `callback(...args)`. Then, we extend the original return value with one additional filed `gtm`.

```javascript
import BrowserDatabase from 'Util/BrowserDatabase';

const addGtmToConfigReducerInitialState = (args, callback, instance) => {
    // We need to make sure the field "gtm" is an object 
    const { gtm } = BrowserDatabase.getItem('config') || { gtm: {} };

    return {
        ...callback(...args),
        gtm
    };
};

export default {
    'Store/Config/Reducer/getInitialState': {
        'function': addGtmToConfigReducerInitialState
    }
};

```

{% endtab %}
{% endtabs %}

## Pluggable objects

Plugins allow you to proxy **any function or class** of the application, which is bind to a namespace. To bind a an object to a namespace, it should have a leading comment starting with `@namespace`. Upon bind to a namespace one or multiple proxy types will become available.

### Class declaration binding

To bind a class to a namespace, add leading comment to a class. Like this:

```javascript
/* @namespace Component/AddToCart/Container */
export class AddToCartContainer extends PureComponent {
    // ...
}
```

#### You are now able to proxy these object types:

* class methods - `member-function`
* class properties - `member-properties`
* static methods of a class - `static-member`
* class instance itself - `class`

{% hint style="warning" %}

### **Heads Up!**

If you want to plug into a class member that is an arrow function, still use `member-function`, not `member-property`
{% endhint %}

### Function declaration & assignment binding

To bind a function declaration to a namespace add leading comment to it. Like this:

```javascript
/* @namespace Util/Validation/validateHandler */
function validateHandler(/** ... */) {
    // ...
}
```

To bind functions assignment to a namespace:

```javascript
/** @namespace Component/AddToCart/Container/mapStateToProps */
export const mapStateToProps = (state) => ({
    // ...
});
```

You can also do it for arrow functions passed as an argument:

```javascript
fetch(/** ... */).then(
    /** @namespace Component/Braintree/Component/fetchThen */
    () => { /** ... */ } 
);
```

#### You are now able to proxy these object types:

* function - `function`

## File structure

The application plugin declarations must be located inside of your extension's folder `src/plugin`. To declare a plugin inside of this folder, you must name it with a `plugin` post-fix. For example: `CartQuery.plugin.js`.

## Plugin configuration syntax

For a plugin to work, it should **export default an object of configuration**. The configuration object is structured the following way:

* object keys are the namespaces you intend to apply proxy to
* object values are objects, which define the type of proxy to apply&#x20;

For example:

```javascript
export default {
    'Framework/Component/App/Component': {
        'class': proxyImplmentations,
        'member-property': {
            contextProviders: proxyImplmentations
        }
    }
};
```

In this case, the object has only one key - `Framework/Component/App/Component` which references an object [bind to this namespace](https://docs.create-scandipwa-app.com/extensions/application-plugins#pluggable-objects). We know this object is a class declaration, therefore we are now allowed to use the [class-declaration proxy types](https://docs.create-scandipwa-app.com/extensions/application-plugins#you-are-now-able-to-proxy-these-object-types). We utilize `class` and `member-property` types.&#x20;

{% hint style="info" %}
The proxy types`member-function`, `member-properties`, `static-member`require additional configuration object. This object is structured as follows:

* object keys are the method or property names you want to provide a proxy for
* object values are proxy function implementations

Other proxy types can be assigned to a proxy function implementation directly.
{% endhint %}

### Proxy implementation syntax

The `proxyImplmentations` used in the example can be:

* A function implementing a proxy
* An object with `position` and `implementation` keys, where:
  * `position` is a numerical position of a plugin (default is `100`)
  * `implementation` is a function implementing a proxy

You can also provide an array of above types.

## Proxy function implementation types

Each proxy type expects a function with a different set of arguments. Here is an overview of function implementations for each proxy type:

{% tabs %}
{% tab title="member-function" %}
The class method proxy implementation function takes:

* An array of **arguments** from the caller
* **Callback** - an original method&#x20;
* **Instance** - the original class instance

An example of such function is:

```javascript
(args, callback, instance) => {
    // TODO: implement
}
```

{% endtab %}

{% tab title="member-properties" %}
The class property proxy implementation function takes:

* **Member** - an original value of the class property
* **Instance** - the original class instance

An example of such function is:

```javascript
(member, instance) => {
    // TODO: implement
}
```

{% endtab %}

{% tab title="static-member" %}
The static class method proxy implementation function takes:

* An array of **arguments** from the caller
* **Callback** - an original method&#x20;

An example of such function is:

```javascript
(args, callback) => {
    // TODO: implement
}
```

{% endtab %}

{% tab title="class" %}
The class proxy implementation function takes:

* **Class** - a class you intend to modify *(not an instance!)*

An example of such function is:

```javascript
(Class) => {
    // TODO: implement
}
```

{% endtab %}

{% tab title="function" %}
The function proxy implementation function takes:

* An array of **arguments** from the caller
* **Callback** - an original method&#x20;
* **Context** - the original context of a function

An example of such function is:

```javascript
(args, callback, context) => {
    // TODO: implement
}
```

{% endtab %}
{% endtabs %}


# Plugin Templates

Copy-pastable example snippets for accelerating plugin development

## Method of a component

In this example - `render`

```javascript
const render = (args, callback, instance) => (
   <>
       { callback.apply(instance, args) }
   </>
);

export default {
   'Component/NAME/Component': {
       'member-function': {
           render
       }
   }
};
```

## Container functions

Common case - when you need to pass an additional function from parent to child

```javascript
export class NAMEContainerPlugin {
   containerFunctions = (originalMember, instance) => ({
       ...originalMember,
       handleSomething: this.handleSomething.bind(instance)
   });

   handleSomething(arg) {
       console.log(arg);
   }
}

const { containerFunctions } = new NAMEContainerPlugin();

export default {
   'Component/NAME/Container': {
       'member-property': {
           containerFunctions
       }
   }
};
```

## Prop types

You need to add an additional prop to `propTypes` after passing an additional prop to the component? No problem!&#x20;

```javascript
import PropTypes from 'prop-types';

const propTypes = (originalMember) => ({
   ...originalMember,
   handleSomething: PropTypes.func.isRequired
});

export default {
   'Component/NAME/Component': {
       'static-member': {
           propTypes
       }
   }
};
```

## Default props

Not required new propType - do this.

```javascript
const defaultProps = (originalMember) => ({
   ...originalMember,
   pluginProp: 'PluginProp'
});

export default {
   'Component/NAME/Container': {
       'static-member': {
           defaultProps
       }
   }
};
```

## More state

Additional fields for the state.

```javascript
const state = (originalMember) => ({
   ...originalMember,
   PluginState: 'PluginState'
});

export default {
   'Component/NAME/Container': {
       'member-property': {
           state
       }
   }
};
```

## Adding a Reducer to the Redux Store

Add reducers to the application as follows.&#x20;

```javascript
import { NAMEReducer } from '../store/NAME;

const getStaticReducers = (args, callback, instance) => ({
   ...callback(...args),
   NAMEReducer
});

export const config = {
   'Store/Index/getReducers': {
       function: getStaticReducers
   }
};

export default config;
```

## Query fields

Additional query field shown below!

```javascript
const _getMETHODFields = (args, callback, instance) => [
   ...callback.apply(instance, args),
   'field_name'
];

export default {
   'Query/NAME': {
       'member-function': {
           _getMETHODFields
       }
   }
};
```

## Reducer Initial State

```javascript
const getInitialState = (args, callback, instance) => (
    {
        ...callback(...args),
        new_state: 'true'
    }
);

export default {
    'Store/NAME/Reducer/getInitialState': {
        function: getInitialState
    }
};
```

## mapStateToProps

Connect an additional piece of state to the component

```javascript
const mapStateToProps = (args, callback, instance) => {
   const [state] = args; 

   return {
       ...callback(...args),
       pluginProp: state.SomeReducer.someState
   };
};

export default {
   'Component/NAME/Container/mapStateToProps': {
       function: mapStateToProps
   }
};
```

## mapDispatchToProps

Connect an additional dispatch function to the component

```javascript
const { letsDoSomething } = import('Store/STORENAME/STORENAME.action');

const mapDispatchToProps = (args, callback, instance) => {
   const [dispatch] = args;

   return {
       ...callback(...args),
       doSomething: (value) => dispatch(letsDoSomething(value))
   };
};

export default {
   'Component/NAME/Container/mapDispatchToProps': {
       function: mapDispatchToProps
   }
};
```

## Adding a Route to the Router

Note how we use async `import(...)` statement here in order to optimize bundle sizes!

```javascript
import { lazy } from 'react';
import { Route } from 'react-router-dom';

import { withStoreRegex } from 'Component/Router/Router.component';

export const YourPage = lazy(() => import(
    /* webpackMode: "lazy", webpackChunkName: "extension-name" */ 
    '../route/YourPage'
));

const SWITCH_ITEMS_TYPE = (originalMember) => [
   ...originalMember,
   {
       component: (
           <Route
             path={ withStoreRegex('/path') }
             render={ (props) => <YourPage { ...props } /> }
           />
       ),
       position: 100
   }
];

export const config = {
   'Component/Router/Component': {
       'member-property': {
           SWITCH_ITEMS_TYPE
       }
   }
};

export default config;
```

## Extending maps

Example: creating a new tab in MyAccount

```javascript
import { lazy } from 'react';

import { 
    MY_TAB_PATH,
    MY_TAB_NAME
} from '../component/MyAccountCustomTab/MyAccountCustomTab.config';

import MyAccountCustomTab from '../component/MyAccountCustomTab';

const renderMap = (originalMember) => ({
   [MY_TAB_NAME]: MyAccountCustomTab,
   ...originalMember,
});

const tabMap = (originalMember) => ({
   ...originalMember,
   [MY_TAB_NAME]: {
       url: `/${ MY_TAB_PATH }`,
       name: __('My Tab')
   }
});

export default {
   'Route/MyAccount/Container': {
       'static-member': {
           tabMap
       }
   },
   'Route/MyAccount/Component': {
       'member-property': {
           renderMap
       }
   }
};
```


# Build configuration plugins

ScandiPWA introduces concept of "build plugins". **This is a feature of** [**ScandiPWA extensions**](https://docs.create-scandipwa-app.com/extensions/extensions).&#x20;

{% hint style="info" %}
**To create a build plugin** - means to create extend the application build configuration. The build plugins can modify: [Webpack](https://webpack.js.org/), [Webpack dev-server](https://webpack.js.org/configuration/dev-server/), [Craco](https://github.com/gsoft-inc/craco/) configurations. You can also provide commands to run before starting the build.
{% endhint %}

## To create a build plugin

{% tabs %}
{% tab title="Instruction" %}

1. Define an empty object as a value of the `scandipwa.build` field in your extension's `package.json`
   1. Populate the configuration object with `cracoPlugins` field, set it to empty array.
2. Create a new folder in your extension's root, name it `build-config`:
   1. Create a new file in it, name it to represent it's build modification purpose
   2. Populate an array of `cracoPlugins` in your `package.json` with a path to your new file (relative to the extension root).
3. Inside of your plugin file, define a `module.exports` equal to an object. This object may have two keys:
   1. `plugin` (*required*) where the plugin implementation will be defined
   2. `options` (*optional*) where the plugin options will be defined
4. Implement a plugin in the object created at the step 3). To do it, follow [these guidelines](https://docs.create-scandipwa-app.com/extensions/build-configuration-plugins#build-plugin-implementation-syntax).

{% hint style="info" %}
You can also use the existing Craco extensions. You can find [the list of them here](https://github.com/gsoft-inc/craco#community-maintained-plugins). You can import them and use as the plugin implementation passing into the `plugin` key value on the step 3).
{% endhint %}
{% endtab %}

{% tab title="Example" %}
This plugin implements a Create ScandiPWA App compilation into valid Magento 2 theme. We plan to modify the Webpack and Craco configurations.

Following instruction steps 1) and 2) we created following entry in our `package.json`:

```javascript
{
    "scandipwa": {
        "type": "extension",
        "build": {
            "cracoPlugins": [
                "build-config/magento.js"
            ]
        }
    },
    ...
}
```

The new file `magento.js` was created in `build-config` folder in our extension root.

In our `magento.js` plugin file, we define a `module.exports` an object, with plugin key, where we implement extensions of Webpack and Craco configurations. We make sure:

* The `appBuild` should is set to `magento/Magento_Theme`.
* The `appHtml` to `public/index.php`.
* The options field `filename` of the `HtmlWebpackPlugin` is set to `../templates/root.phtml`.
* The `file-loader` is excluding the `.php` from processing, so it does not appear in the build folder along-side of others application assets.

{% hint style="info" %}
We used `getLoader` and `loaderByName` utility functions of Craco. Learn more about them in [official Craco guide](https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#utility-functions).
{% endhint %}

{% hint style="warning" %}

### Heads up!

Create ScandiPWA App uses the custom fork of Craco called `@scandipwa/craco`.
{% endhint %}

The final file will look something like this:

```javascript
const path = require('path');
const FallbackPlugin = require('@scandipwa/webpack-fallback-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { sources } = require('@scandipwa/scandipwa-scripts/lib/sources');
const { getLoader, loaderByName } = require('@scandipwa/craco');

module.exports = {
    plugin: {
        overrideCracoConfig: ({
            cracoConfig
        }) => {
            // For Magento, use magento/Magento_Theme folder as dist
            cracoConfig.paths.appBuild = path.join(process.cwd(), 'magento', 'Magento_Theme', 'web');

            // For Magento use PHP template (defined in /public/index.php)
            cracoConfig.paths.appHtml = FallbackPlugin.getFallbackPathname('./public/index.php', sources);

            // Always return the config object.
            return cracoConfig;
        },
        overrideWebpackConfig: ({ webpackConfig }) => {
            // For Magento setup, change output file name
            webpackConfig.plugins.forEach((plugin) => {
                if (plugin instanceof HtmlWebpackPlugin) {
                    plugin.options.filename = '../templates/root.phtml';
                }
            });

            const { isFound: isFileLoaderFound, match: fileLoader } = getLoader(
                webpackConfig,
                loaderByName('file-loader')
            );

            if (isFileLoaderFound) {
                // Add .php to ignore files (otherwise php will compile into /media as file)
                fileLoader.loader.exclude.push(/\.php$/);
            }

            return webpackConfig;
        }
    }
};
```

{% endtab %}
{% endtabs %}

## To define a before run script

{% tabs %}
{% tab title="Instruction" %}

1. Define an empty object as a value of the `scandipwa.build` field in your extension's `package.json`
   1. Populate the configuration object with `before` field, set it to empty string.
2. Create a new folder in your extension's root, name it `build-config`:
   1. Create a new file in it, name it to represent before-run script's purpose
   2. Set the `before` field in your `package.json` equal to a path to your new file (relative to the extension root).
3. Inside of your plugin file, define a `module.exports` equal to a function.
4. Implement a script based on your needs. No guidelines here, it's up to you!
   {% endtab %}

{% tab title="Example" %}
The purpose of our script is to make sure there is a file named `composer.json` in the root current theme.

Following instruction steps 1) and 2) we created following entry in our `package.json`:

```javascript
{
    "scandipwa": {
        "type": "extension",
        "build": {
            "before": "build-config/composer.js"
        }
    },
    ...
}
```

The new file `composer.js` was created in `build-config` folder in our extension root.

Inside of this file we will use the `process.cwd()` to determine the location of current theme. We will use `process.exit()` to exit the program and stop build from running.

The final file will look something like this:

```javascript
const fs = require('fs');
const path = require('path');

module.exports = () => {
    const composerPath = path.join(process.cwd(), 'composer.json');
    
    if (!fs.existsSync(composerPath)) {
        console.log('The file "composer.json" should be present it the theme\'s root');
        process.exit();
    }
};
```

{% endtab %}
{% endtabs %}

## Build plugin implementation syntax

The plugin syntax of Create ScandiPWA App is based on the [Craco](https://github.com/gsoft-inc/craco) (**C**reate **R**eact **A**pp **C**onfiguration **O**verride) plugin syntax.

Each plugin is an object, which might contain following keys (you can combine them):

* `overrideCracoConfig` -  allows to customize the Craco configuration object.&#x20;
* `overrideWebpackConfig` - allows to customize the Webpack config.
* `overrideDevServerConfig` - allows to customize the Webpack dev-server config

The values of this object keys are functions, which implement an override for the configuration. The function **may be asynchronous**.

### Craco configuration plugin

{% tabs %}
{% tab title="Instruction" %}
The function `overrideCracoConfig` allows a plugin override the configuration object **before** it's process by Craco.

The function **must return a valid Craco configuration object***.* The function will be called with a single object argument having the following structure:

```javascript
{
    cracoConfig, // The original CRACO configuration object
    pluginOptions, // The plugin options provided by the consumer
    context: {
        env, // The current NODE_ENV (development, production, etc..)
        paths // An object that contains all the paths used by CRA
    }
}
```

{% hint style="info" %}
The `cracoConfig` is passed into you plugin implementation by reference, which means you can modify it's values directly.
{% endhint %}
{% endtab %}

{% tab title="Example" %}
This plugin intent is to modify the paths of an application. The `appBuild` should be set to `magento/Magento_Theme` and the `appHtml` to `public/index.php`.

```javascript
({ cracoConfig }) => {
    // For Magento, use magento/Magento_Theme folder as dist
    cracoConfig.paths.appBuild = path.join(process.cwd(), 'magento', 'Magento_Theme', 'web');
    
    // For Magento use PHP template (defined in /public/index.php)
    cracoConfig.paths.appHtml = FallbackPlugin.getFallbackPathname('./public/index.php', sources);
    
    // Always return the config object.
    return cracoConfig;
}
```

{% endtab %}
{% endtabs %}

### Webpack configuration plugin

{% tabs %}
{% tab title="Instruction" %}
The function `overrideWebpackConfig` allows plugin override the Webpack configuration object **after** it's been customized by Craco.

The function **must return a valid Webpack configuration object**. The function will be called with a single object argument having the following structure:

```javascript
{
    webpackConfig, // The webpack config object already customized by craco
    cracoConfig, // The configuration object read from the craco.config.js file provided by the consumer
    pluginOptions, // The plugin options provided by the consumer
    context: {
        env, // The current NODE_ENV (development, production, etc..)
        paths //An object that contains all the paths used by CRA
    }
}
```

{% hint style="info" %}
The `webpackConfig` is passed into you plugin implementation by reference, which means you can modify it's values directly.
{% endhint %}
{% endtab %}

{% tab title="Example" %}
The plugin modifies the options field `filename` of the `HtmlWebpackPlugin`. It set's it to `../templates/root.phtml`.

```javascript
({ webpackConfig }) => {
    // For Magento setup, change output file name
    webpackConfig.plugins.forEach((plugin) => {
        if (plugin instanceof HtmlWebpackPlugin) {
            plugin.options.filename = '../templates/root.phtml';
        }
    });

    // Always return the config object.    
    return webpackConfig;
}
```

{% endtab %}
{% endtabs %}

### Webpack dev-server configuration plugin

{% tabs %}
{% tab title="Instruction" %}
The function `overrideDevServerConfig` let a plugin override the dev server config object after it's been customized by Craco.

The function **must return a valid Webpack dev-server configuration object**. The function will be called with a single object argument having the following structure:

```javascript
{
    devServerConfig, // The dev server config object already customized by craco
    cracoConfig, // The configuration object read from the craco.config.js file provided by the consumer
    pluginOptions, // The plugin options provided by the consumer
    context: {
        env, // The current NODE_ENV (development, production, etc..)
        paths, // An object that contains all the paths used by CRA
        allowedHost // Provided by CRA
    }
}
```

{% endtab %}

{% tab title="Example" %}
This plugin dumps the configuration object of Webpack dev-server for debugging purposes.

```javascript
({ devServerConfig }) => {
    // Dump the configuration file and format it
    console.log(JSON.stringify(devServerConfig, null, 4));
    
    // Always return the config object.
    return devServerConfig;
}
```

{% endtab %}
{% endtabs %}


# Plugins for HTML and PHP

The [@scandipwa/scandipwa-template-plugin-system](https://github.com/scandipwa/create-scandipwa-app/tree/master/build-packages/scandipwa-template-plugin-system) package provides the template plugin system used by [Create Scandipwa App](https://github.com/scandipwa/create-scandipwa-app).

#### Abstract <a href="#abstract" id="abstract"></a>

This template plugin system processes the template (the main markup file) file of the application.

It provides an opportunity to modify the template similarly to the process which is provided by CSA to modify the build configuration.

#### Use cases <a href="#use-cases" id="use-cases"></a>

1. Your extension needs some additional HTML/PHP nodes in the template
2. Your extension is incompatible with some existing HTML/PHP nodes in the template and needs to remove them
3. Your extension needs to change attributes of the existing nodes to some other values

#### Limitations <a href="#limitations" id="limitations"></a>

1. This tool is not meant for PHP code modifications. It offers an opportunity to interact with template as with text, but changing PHP or JS code such way would be considered a misuse, due to possible incompatibilities with a plugin written such a way. To change the PHP logic - change abstractions, not delta-modify the code.

#### Dependencies <a href="#dependencies" id="dependencies"></a>

`xmldom` is used to parse the markup to DOM and parse the DOM to markup. The DOM provided in the API is documented in this package's documentation.

`lodash` is used to process the initial template the same way as the loader of the `HtmlWebpackPlugin` does that.

#### How to use <a href="#how-to-use" id="how-to-use"></a>

1. Define the paths to the template plugins in your package.json

```
{
    "scandipwa": {
        "build": {
            "templatePlugins": [
                "build-config/template-modification"
            ]
        }
    },
}
```

1. Use one of the provided APIs to modify the template
2. See the modified template in the compiled version of your project

#### API reference <a href="#api-reference" id="api-reference"></a>

The processing happens during the build time. Don't let the API (which is really similar to what browsers have for DOM) trick you!

1. `overrideDOM({ dom, parser, serializer }): DOM`

Interact with the DOM representation of the template. This is a **recommended** way to modify a template using this plugin system.

The DOM is parsed by the `xmldom` package, see [its documentation](https://www.npmjs.com/package/xmldom) for some precise information on the deeper API.

This API covers all of the regular needs: handling the DOM including additional interactions with PHP nodes.

A valid DOM should be returned from this method.

1. `overrideText({ markup }): string`

Interact with the text representation of the template. It is **not recommended** to use this if you have an opportunity to use the first API.

This API is meant strictly for interaction with template types that are **not supported** by the first API, e.g. `cshtml`, Razor syntax etc.

Such plugins will be executed after the DOM plugins. A valid markup should be returned from this method.

#### Usage examples <a href="#usage-examples" id="usage-examples"></a>

1. Adding an additional tag to the document

```javascript
module.exports = {
    templatePlugin: {
        overrideDOM({ dom, parser, serializer }) {
            // Generate the node as you would do that in the browser scope
            const additionalLink = dom.createElement('link');
            additionalLink.setAttribute('rel', 'stylesheet');
            additionalLink.setAttribute('href', 'https://my-super-source/style.css');

            // Or parse it directly from the markup!
            const additionalLink = parser.parseFromString(
                `<link rel="stylesheet" href="https://my-super-source/style.css">`
            );

            // Modify the DOM that is going to be present in the application
            dom.getElementsByTagName('head')[0].appendChild(additionalLink);

            // Remember to always return DOM from this method!
            return dom;
        }
    }
};
```

1. Adding additional non-supported by DOM syntax to the document

```javascript
module.exports = {
    templatePlugin: {
        overrideText({ markup }) {
            const additionalText = `@{
                var greeting = "Welcome to our Razor-powered website!";
            }`;

            return additionalText.concat(markup);
        }
    }
};
```


# File provision

ScandiPWA introduces concept of "file provisioning". **This is a feature of** [**ScandiPWA extensions**](https://docs.create-scandipwa-app.com/extensions/extensions).&#x20;

{% hint style="info" %}
**To provision a file** - means to add a file into the "override" tool-chain with a lowest priority. This would make it discoverable by compiler, while any theme will be able to easily override it.
{% endhint %}

This is commonly used by extensions which implement changes in the entry-point. In example, `@scandipwa/m2-theme` provisions the `pub/index.php` path. It makes it possible to compile an application using this as an HTML entry-point without manually defining it in a theme.

To provision a file, set the `scandipwa.provide` field of `package.json` equal to an array, and populate it with desired path to provision.&#x20;


# Module preference

ScandiPWA introduces concept of module preference. **This is a feature of** [**ScandiPWA extensions**](https://docs.create-scandipwa-app.com/extensions/extensions).&#x20;

{% hint style="info" %}
**To preference a module** - to take-over another NPM or virtual module. To take-over means to completely replace an implementation, the original module will not be available.
{% endhint %}

To preference a module, set the `scandipwa.preference`  field of `package.json` equal to the desired module name.

{% hint style="danger" %}

### Watch out!

This is very dangerous to preference a real NPM module, like in example `react` or `redux`. While you can do this, this feature is meant for [virtual module preference](https://docs.create-scandipwa-app.com/extensions/extensions#virtual-module-preference).
{% endhint %}

### &#x20;Virtual module preference

{% hint style="danger" %}

### Watch out!

This is a subject to change. We plan on providing a more robust way to depend on virtual modules. **They should be coupled with typescript interfaces**. Currently, virtual-modules only work on the level of module resolution, they do not provide any interface for the implementation.&#x20;
{% endhint %}

Create ScandiPWA App introduces the concept of "virtual module".

{% hint style="info" %}
**Virtual module** - a non-existing module, referenced in the code. It provides an abstraction layer, which allows to swap the implementation.
{% endhint %}

Virtual modules are useful for UI elements, where different libraries could be used as an implementation, or for an API endpoints, where the application is relying on data format, not the source of the data.

To create a virtual module, define the reference to a non existing module, and [implement a preference](https://docs.create-scandipwa-app.com/extensions/extensions#extension-module-preference) in your extension to it. To ensure that it does not exist, use `@virtual-module/<name>` name for it.


# Proxying requests to server

People often serve the front-end ScandiPWA app from the same host and port as their backend implementation (i.e. Magento theme).

For example, a production setup might look like this after the app is deployed:

```
/* - static server returns index.html with ScandiPWA app
/graphql - Magento 2 server handles any GraphQL reuqests
/media - Magento 2 server handles any media asset requets
```

Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/graphql')` without worrying about redirecting them to another host or port during development.

To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example:&#x20;

```javascript
"proxy": "http://localhost:4000",
```

This way, when you `fetch('/graphql')` in development, the development server will recognize that it’s not a static asset and will proxy your request to `http://localhost:4000/graphql` as a fallback. The development server will **only** attempt to send requests without `text/html` in its `Accept` header to the proxy.

## Configuring proxy manually

If the `proxy` option is **not** flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware.

You can use this feature in conjunction with the `proxy` property in `package.json`, but it is recommended you consolidate all of your logic into `src/setupProxy.js`.

First, install `http-proxy-middleware` using npm or Yarn:

```bash
npm install http-proxy-middleware --save # for NPM
yarn add http-proxy-middleware # for Yarn
```

Next, create `src/setupProxy.js` and place the following contents in it:

```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  // ...
};
```

You can now register proxies as you wish! Here's an example using the above `http-proxy-middleware`:

```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/graphql',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

```

{% hint style="warning" %}

### Heads up!

You do not need to import this file anywhere. It is automatically registered when you start the development server.
{% endhint %}

## Configuring the Magento 2 server

To proxy requests to the Magento 2 server, you are required to make sure that it is using the correct Composer dependencies. The list of your application Composer dependencies can be found in your application `composer.json` file.

You can copy the requirements defined in `require` field of your application's `composer.json` to your server's root `composer.json`  and execute the `composer update` command.

In case you plan on deploying ScandiPWA as a Magento theme, you might simply require the ScandiPWA's composer package and it will be registered in Magento as the valid theme. Read more about this process in the [Magento theme deployment guide](https://docs.create-scandipwa-app.com/deploying-your-app/magento-theme#deploying-from-local-composer-repository).


# Internationalization

{% hint style="info" %}
**Internationalization** - also known as "translation", "i18n" – is a process of making your application international.
{% endhint %}

The NPM package `@scandipwa/webpack-i18n-runtime` is responsible for this mechanics in the Create ScandiPWA App ecosystem.

## To create a new translation for your application

{% tabs %}
{% tab title="Instructions" %}

1. Make sure the `@scandipwa/webpack-i18n-runtime` is installed and enabled by following [this guide](https://docs.create-scandipwa-app.com/building-your-app/internationalization#installing-the-package).
2. Make sure your code is translatable, follow the ["Writing translatable code" guide](https://docs.create-scandipwa-app.com/building-your-app/internationalization#writing-translatable-code).
3. [Propagate](https://docs.create-scandipwa-app.com/building-your-app/internationalization#selecting-the-locales-to-compile) the field `scandipwa.locales` in `package.json` with desired locales to compile.
4. Run the application in production or development mode at least once. This will [create the translation files](https://docs.create-scandipwa-app.com/building-your-app/internationalization#creating-translation-files) in `i18n` folder of your application. It will also [warn you, if some translations are duplicated, invalid or missing](https://docs.create-scandipwa-app.com/building-your-app/internationalization#useful-build-time-information).
5. Propagate the internationalization files with proper translations. Some translations may already be present - [parent themes and extensions can provide these values](https://docs.create-scandipwa-app.com/building-your-app/internationalization#translation-sources).
   {% endtab %}

{% tab title="Example" %}
Let's assume we are also starting with blank repository, whose [parent theme](https://docs.create-scandipwa-app.com/themes/extensions-and-themes#parent-theme) is `@scandipwa/scandipwa`. Let's assume we are using `@scandipwa/scandipwa` of version `4.0.1`.&#x20;

1. We are using `@scandipwa/scandipwa` of version equal or higher than the `4.0.1` therefore, the `@scandipwa/webpack-i18n-runtime` extension is already installed and enabled.
2. We did no modification to source code (our theme is blank), therefore we assume that the source code of `@scandipwa/scandipwa` is written in translatable fashion. Indeed, most files contain proper translations, in example: [`AddToCart`](https://github.com/scandipwa/scandipwa/blob/%40scandipwa/scandipwa%404.0.1/packages/scandipwa/src/component/AddToCart/AddToCart.component.js#L71-L72).
3. Let's add (enable) the `ru_RU` locale in the `package.json`'s field `scandipwa.locales` as follows:

   ```javascript
   {
       "scandipwa": {
           "locales": {
               "en_US": true,
               "ru_RU": true
           }
       }
   }
   ```
4. Let's run the application, it should warn us about all missing translations in case they present. Ideally there should be no invalid translations, but in case there are we should address them. **This will not however break the application**.
5. Now we can modify and add translations in `i18n/ru_RU.json` of our theme.
   {% endtab %}
   {% endtabs %}

## Installing the package

{% hint style="warning" %}

### Heads up!

This internationalization mechanism is included into the `@scandipwa/scandipwa` theme since version `4.0.1` and above. In case of custom project, you must install and enable it manually.
{% endhint %}

To get this mechanism up and running, you need to:

:zap: **Install** the module

```bash
# For yarn users
yarn add @scandipwa/webpack-i18n-runtime

# For npm users
npm i @scandipwa/webpack-i18n-runtime
```

:zap:**Enable** it as a `scandipwa` extension

```javascript
{
    "scandipwa": {
        "extensions": {
            "@scandipwa/webpack-i18n-runtime": true
        }
    }
}
```

## Writing translatable code

In the application, all the translatable strings should get wrapped into the `__(...)` translation function. Every string wrapped into this function will be available to translate inside of your translation files.

The function is globally provided, you do not need to import it manually.

```jsx
    /** This is NOT translatable! */
    render() {
        return <p>My Account</p>
    }

    /** This is NOT translatable as well! */
    render() {
        return <p>{ 'My Account' }</p>
    }

    /** This IS translatable! */
    render() {
        return <p>{ __('My Account') }</p>
    }
```

## Specifying the locales to compile

When invoking the compilation, you should specify the locales you are willing to compile in the `package.json` file of your theme, as follows:

```javascript
{
    "scandipwa": {
        "locales": {
            "en_US": true,
            "fr_FR": true
        }
    }
}
```

## Creating translation files

If a translation for the given locale is not found in your theme, it is automatically created as `./i18n/${locale}.json` during the build time.

Then, it gets replenished with all the non-translated values from the compiled theme.

The default locale is `en_US`. No translation files will be automatically generated for this locale. You may create a translation file for the default locale manually, usually, it is not necessary.

## Translation sources

During the compilation time, the translations are collected from several sources and merged together. A chunk is generated for each locale code.

If the same string is translated in multiple translation files, the ones with higher position (from listed below) overwrite the ones with lower position. Exception for this rule: falsy (e.g, `null`, `undefined`, `""`) values can be overwritten even from a file with lower priority.

The order is as follows:

1. Child theme
2. Parent themes from youngest (e.g. father) to the oldest (e.g. grandfather)
3. Extensions

{% hint style="info" %}
**Translations in extensions** - it is allowed (and, in most cases, necessary) to have translations inside of extensions. To do that, you need to put a translation file for your extension into that extension's `i18n/${locale}.json` file.
{% endhint %}

## Useful build-time information

After a successful compilation, you will be presented with any information on the following matters:

1. **Unused translations** - it is not recommended polluting your translation files with unused translations, this plugin will point out any translation strings in your theme that are not used in the application. It is recommended to remove them. You will not be see such information about your plugins or parent themes.
2. **Missing translations** - if your application lacks any translations, you are going to be warned about it. You will be provided this information about your theme only.
3. **Corrupted translation files** - if any of your files are corrupted, i.e. not `JSON.parse`able, you are going to be warned about it as well.
4. **Overwriting falsy value by translation with lower priority** - e.g. if your theme's translation file contains `"Account": null` (any falsy value, not only null) and some parent theme or extension's one contains `"Account": "Compte"`, the second one will be taken (even though the priority is lower for that one) and you will get alarmed about it.

## How to enable the translations on my page

After installing the translations, please follow this guide to enable them.

{% embed url="<https://manual.scandipwa.com/basic-configuration/store-details/locale-options>" %}

{% hint style="warning" %}

### Heads up!

If you don't have a local backend and start frontend in normal mode, you should add `defaultLocale` to your `index.html` file.
{% endhint %}

```javascript
<script>
  window.defaultLocale = 'en_US';
</script>
```


# Creating production build

To create a production build of your theme, you must run the build command:

```
npm run build
```

This creates a `build` directory with a production build of your app. Inside the `build/static` directory will be your JavaScript and CSS files. Each filename inside of `build/static` will contain a unique hash of the file contents. This hash in the file name enables [long term caching techniques](https://create-react-app.dev/docs/production-build#static-file-caching).

{% hint style="warning" %}

### **Heads Up!**

When [compiled as Magento 2 theme](https://docs.create-scandipwa-app.com/deploying-your-app/magento-theme), the production build directory is changed to `magento/Magento_Theme`.&#x20;
{% endhint %}

## JavaScript chunks

When running a production build of freshly created Create React App application, there are a number of `.js` files (called *chunks*) that are generated and placed in the `build/static/js` directory:

`main.[hash].chunk.js`

* This is your application code. `index.js`, etc.

`[name].[hash].chunk.js`

* These files are **code-splitting** chunks. The code inside them includes modules that you've imported using the [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand) or following [`React.lazy`](https://reactjs.org/docs/code-splitting.html#reactlazy) approach.

`[number].[hash].chunk.js`

* These files are **vendor** chunks. The code inside them includes modules that you've imported from within `node_modules`. Since vendor code tends to change less often than the actual application code, the browser will be able to cache them separately, and won't re-download them each time the app code changes.

`runtime-main.[hash].js`

* This is a small chunk of [webpack runtime](https://webpack.js.org/configuration/optimization/#optimization-runtimechunk) logic which is used to load and run your application. The contents of this will be embedded in your `build/index.html` file by default to save an additional network request.

## CSS chunks

Similarly with JavaScript in production, there are a number of `.css` files (called *chunks*) that are generated and placed in the `build/static/css` directory:

`[name].[hash].chunk.css`

* These files are **code-splitting** chunks. The code inside them includes CSS modules that you've imported in JavaScript modules imported using the [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand) or following [`React.lazy`](https://reactjs.org/docs/code-splitting.html#reactlazy) approach.

`[number].[hash].chunk.css`

* These files are **vendor** chunks. The code inside them includes CSS modules that you've imported from within `node_modules`.&#x20;

`main.[hash].chunk.css`

* This are styles imported in your application. `index.js`, etc.


# Storefront

[ScandiPWA theme](https://docs.create-scandipwa-app.com/themes/extensions-and-themes) is capable of being bundled into the storefront.

{% hint style="info" %}
**Storefront** - a stand-alone deployment of your e-commerce platform front-end. The storefront main goal is to display the data coming from e-commerce platform API. The storefront is not the data-source, rather data-presentation.
{% endhint %}

Creating a storefront build is simple. It works out-of-the-box with any application created using Create ScandiPWA App. All you need to do is to bundle it using the [production build command](https://docs.create-scandipwa-app.com).

## Deploying the Storefront

The main challange of deploying ScandiPWA as a storefront is to properly configure the [proxy to existing Magento 2 instance](https://create-react-app.dev/docs/proxying-api-requests-in-development/). This is automatically done in development, however in production, you must configure it yourself.

### Using the CLI

To deploy an application to the **FREE** ScandiPWA static-hosting, you can use [ScandiPWA CLI](broken://pages/-MMa4JsVvBMbamKNarro). In order to do it, simply type-in following command from your theme's root:

```
scandipwa deploy
```

This will return you a link to your instance and update the `package.json` file with the `scandipwa.staticDeploy` field. This field makes you application deployment persistent. Next time you run this command, the changes will be reflected on the same instance.

The application will proxy all requests to the Magento server you defined in the `proxy` field of your `package.json`.

### Using the express server

This approach is a little-bit more complex. In order to do it you will need to install the `express` server and `http-proxy-middleware` as your theme's dependency. To do it, run:

```bash
npm i express http-proxy-middleware # for NPM
yarn add express http-proxy-middleware # for Yarn
```

Then create a new file `server.js` in the application root. Inside, paste following:

```javascript
const express = require('express');
const path = require('path');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

app.use(express.static(path.join(__dirname, 'build')));

app.use(['/graphql', '/media'], createProxyMiddleware({
    target: require('package.json').proxy,
    changeOrigin: true
}));

app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(9000);
```

Now, [create a production build](https://docs.create-scandipwa-app.com/building-your-app/creating-production-build). Then, start the server:

```javascript
node server.js
```

The application will proxy all requests to the Magento server you defined in the `proxy` field of your `package.json`.


# Magento theme

[ScandiPWA theme](https://docs.create-scandipwa-app.com/themes/extensions-and-themes) is capable of being bundled into the valid Magento theme. However, in order to do it, the theme must have the `@scandipwa/m2-theme` extension installed.

{% hint style="warning" %}

### Heads up!

The `@scandipwa/m2-theme` extension is bundled by default with `@scandipwa/scandipwa` starting from version `2.3.5` and onward. You do not need to install this extension separately if your parent theme is set to`@scandipwa/scandipwa`.
{% endhint %}

In order to install this extension, run [ScandiPWA CLI](https://docs.scandipwa.com/developing-with-scandi/developer-tools/scandipwa-cli) command from the theme root:

```
scandipwa extension install @scandipwa/m2-theme
```

Enabling this extension will allow your ScandiPWA to behave just like the valid Magento 2 theme. If you **set the environment variable `BUILD_MODE` equal to `magento`** the behavior of the `npm run start` and `npm run build` will change.

### `npm run start` or `yarn start`

```bash
BUILD_MODE=magento npm run start # Mac, Linux
set BUILD_MODE=magento && npm run start & set BUILD_MODE= # Windows
```

This command will now watch the files and put their compiled versions into the `magento/Magento_Theme` folder.

### &#x20;`npm run build` or `yarn build`

```bash
BUILD_MODE=magento npm run build # Mac, Linux
set BUILD_MODE=magento && npm run build & set BUILD_MODE= # Windows
```

This command will now create the production build of the application in `magento/Magento_Theme` folder.

## Composer dependencies validation

Additionally, the validation of `composer.json` in the theme root will be activated. The extension will make sure the composer packages specified in the  `scandipwa.composer` filed of your parent themes and extensions `package.json` files are reflected in your theme's `composer.json`. This is required when [connecting to Magento 2 instances](https://docs.create-scandipwa-app.com/building-your-app/proxying-requests-to-server#proxying-requests-to-magento-2-server).

## *Deploying* from local composer repository

To deploy ScandiPWA as Magento 2 theme, you will need a running Magento 2 instance. Copy your ScandiPWA theme with `@scandipwa/m2-theme` extension installed to your Magento 2 server.

1. Build ScandiPWA into Magento theme using the `npm run build` command with `BUILD_MODE` environment variable equal to `magento`. You must do it from the ScandiPWA theme root.
2. From the Magento theme root, add the path to your theme root as a local composer repository. You can use the following command: `composer config repo.theme path <path to scandipwa root>`
3. Now require your theme composer package using the `composer require <composer package name>`. The name of your composer package is defined in `name` field of the `composer.json` file.

## *Developing* from local composer repository

You can also develop ScandiPWA in the Magento theme mode, in order to do that:

1. Disable Magento 2 full-page cache: `bin/magento cache:disable full_page`
2. Start ScandiPWA in development mode using the `npm run start` command with `BUILD_MODE` environment variable equal to `magento`. You must do it from the ScandiPWA theme root.
3. From the Magento theme root, add the path to your theme root as a local composer repository. You can use the following command: `composer config repo.theme path <path to scandipwa root>`
4. Now require your theme composer package using the `composer require <composer package name>`. The name of your composer package is defined in `name` field of the `composer.json` file.


