Skip to content

elegantthemes/divi-extension-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

52 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This project was bootstrapped with Create Divi Extension.

Below you will find some information on how to perform common tasks. You can find the most recent version of this guide here.

Table of Contents

Updating to New Releases

Create Divi Extension is divided into two packages:

  • create-divi-extension is a global command-line utility that you use to create new projects.
  • divi-scripts is a development dependency in the generated projects (including this one).

You almost never need to update create-divi-extension itself: it delegates all the setup to divi-scripts.

When you run create-divi-extension, it always creates the project with the latest version of divi-scripts so you’ll get all the new features and improvements in newly created extensions automatically.

To update an existing project to a new version of divi-scripts, open the changelog, 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 divi-scripts version in package.json and running npm install in this folder should be enough, but it’s good to consult the changelog for potential breaking changes.

We commit to keeping the breaking changes minimal so you can upgrade divi-scripts painlessly.

Sending Feedback

We are always open to your feedback.

Folder Structure

After creation, your project should look like this:

my-extension
├── includes
│   ├── modules
│   │   └── HelloWorld
│   │       ├── HelloWorld.jsx
│   │       ├── HelloWorld.php
│   │       └── style.css
│   ├── loader.js
│   ├── loader.php
│   └── MyExtension.php
├── languages
├── node_modules
├── scripts
│   └── frontend.js
├── styles
├── my-extension.php
├── package.json
└── README.md

For the project to build, these files must exist with exact filenames:

  • includes/loader.js is the JavaScript entry point.

You need to put any JS and CSS files inside includes, scripts, and/or styles, otherwise Webpack won’t see them.

Available Scripts

In the project directory, you can run:

yarn start

Builds the extension in the development mode. Open your WordPress site to view it in the browser. The page will reload if you make edits to JavaScript files. You will also see any lint errors in the console.

yarn build

Builds the extension for production to the build folder. It correctly optimizes the build for the best performance.

yarn zip

Runs build and then creates a production release zip file.

yarn eject

Note: this is a one-way operation. Once you eject, you can’t go back!

If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

Supported Browsers

By default, the generated project uses the latest version of React.

You can refer to the React documentation for more information about supported browsers.

Supported Language Features and Polyfills

This project supports a superset of the latest JavaScript standard.
In addition to ES6 syntax features, it also supports:

Learn more about different proposal stages.

While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so they intend to provide codemods if any of these proposals change in the future.

Note that the project only includes a few ES6 polyfills:

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, or that the browsers you are targeting already support them.

Also note that using some newer syntax features like for...of or [...nonArrayValue] causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use Babel REPL to see what any specific syntax compiles down to.

Syntax Highlighting in the Editor

To configure the syntax highlighting in your favorite text editor, head to the relevant Babel documentation page and follow the instructions. Some of the most popular editors are covered.

Displaying Lint Output in the Editor

Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.

They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.

You would need to install an ESLint plugin for your editor first. Then, add a file called .eslintrc to the project root:

{
  "extends": "divi-extension"
}

Now your editor should report the linting warnings.

Note that even if you edit your .eslintrc file further, these changes will only affect the editor integration. They won’t affect the terminal and in-browser lint output. This is because Create Divi Extension intentionally provides a minimal set of rules that find common mistakes.

If you want to enforce a coding style for your project, consider using Prettier instead of ESLint style rules.

Debugging in the Editor

This feature is currently only supported by Visual Studio Code and WebStorm.

Visual Studio Code and WebStorm support debugging out of the box with Create Divi Extension. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.

Visual Studio Code

You would need to have the latest version of VS Code and VS Code Chrome Debugger Extension installed.

Then add the block below to your launch.json file and put it inside the .vscode folder in your app’s root directory.

{
  "version": "0.2.0",
  "configurations": [{
    "name": "Chrome",
    "type": "chrome",
    "request": "launch",
    "url": "http://localhost:3000",
    "webRoot": "${workspaceRoot}/src",
    "sourceMapPathOverrides": {
      "webpack:///src/*": "${webRoot}/*"
    }
  }]
}

Note: the URL may be different if you've made adjustments via the HOST or PORT environment variables.

Start your extension by running yarn start, and start debugging in VS Code by pressing F5 or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.

Having problems with VS Code Debugging? Please see their troubleshooting guide.

WebStorm

You would need to have WebStorm and JetBrains IDE Support Chrome extension installed.

In the WebStorm menu Run select Edit Configurations.... Then click + and select JavaScript Debug. Paste http://localhost:3000 into the URL field and save the configuration.

Note: the URL may be different if you've made adjustments via the HOST or PORT environment variables.

Start your app by running yarn start, then press ^D on macOS or F9 on Windows and Linux or click the green debug icon to start debugging in WebStorm.

You can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine the same way.

Formatting Code Automatically

Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the Prettier's GitHub page for more information, and look at this page to see it in action.

To format our code whenever we make a commit in git, we need to install the following dependencies:

npm install --save husky lint-staged prettier

Alternatively you may use yarn:

yarn add husky lint-staged prettier
  • husky makes it easy to use githooks as if they are npm scripts.
  • lint-staged allows us to run scripts on staged files in git. See this blog post about lint-staged to learn more about it.
  • prettier is the JavaScript formatter we will run before commits.

Now we can make sure every file is formatted correctly by adding a few lines to the package.json in the project root.

Add the following line to scripts section:

  "scripts": {
+   "precommit": "lint-staged",
    "start": "react-scripts start",
    "build": "react-scripts build",

Next we add a 'lint-staged' field to the package.json, for example:

  "dependencies": {
    // ...
  },
+ "lint-staged": {
+   "src/**/*.{js,jsx,json,css}": [
+     "prettier --single-quote --write",
+     "git add"
+   ]
+ },
  "scripts": {

Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run ./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx,json,css}" to format your entire project for the first time.

Next you might want to integrate Prettier in your favorite editor. Read the section on Editor Integration on the Prettier GitHub page.

Installing a Dependency

The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create Divi Extension as a development dependency. You may install other dependencies with npm:

npm install --save some-other-dependency

Alternatively you may use yarn:

yarn add some-other-dependency

Importing a Component

This project setup supports ES6 modules thanks to Webpack.
While you can still use require() and module.exports, we encourage you to use import and export instead.

For example:

Button.js

import React, { Component } from 'react';

class Button extends Component {
  render() {
    // ...
  }
}

export default Button; // Don’t forget to use export default!

DangerButton.js

import React, { Component } from 'react';
import Button from './Button'; // Import a component from another file

class DangerButton extends Component {
  render() {
    return <Button color="red" />;
  }
}

export default DangerButton;

Be aware of the difference between default and named exports. It is a common source of mistakes.

We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use export default Button and import Button from './Button'.

Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.

Learn more about ES6 modules:

Adding a Stylesheet

This project setup uses Webpack for handling all assets. Webpack offers a custom way of “extending” the concept of import beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to import the CSS from the JavaScript file:

Button.css

.Button {
  padding: 20px;
}

Button.js

import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles

class Button extends Component {
  render() {
    // You can use them as regular CSS styles
    return <div className="Button" />;
  }
}

This is not required for React but many people find this feature convenient. You can read about the benefits of this approach here. However you should be aware that this makes your code less portable to other build tools and environments than Webpack.

In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified .css file in the build output.

Post-Processing CSS

This project setup minifies your CSS and adds vendor prefixes to it automatically through Autoprefixer so you don’t need to worry about it.

For example, this:

.App {
  display: flex;
  flex-direction: row;
  align-items: center;
}

becomes this:

.App {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
      -ms-flex-direction: row;
          flex-direction: row;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

If you need to disable autoprefixing for some reason, follow this section.

Adding Flow

Flow is a static type checker that helps you write code with fewer bugs. Check out this introduction to using static types in JavaScript if you are new to this concept.

Recent versions of Flow work with Create Divi Extension projects out of the box.

To add Flow to a Create Divi Extension project, follow these steps:

  1. Run npm install --save flow-bin (or yarn add flow-bin).
  2. Add "flow": "flow" to the scripts section of your package.json.
  3. Run npm run flow init (or yarn flow init) to create a .flowconfig file in the root directory.
  4. Add // @flow to any files you want to type check (for example, to includes/modules/HelloWorld/HelloWorld.jsx).

Now you can run npm run flow (or yarn flow) to check the files for type errors. You can optionally use an IDE like Nuclide for a better integrated experience.

To learn more about Flow, check out its documentation.

Adding Custom Environment Variables

Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with DIVI_EXTENSION_.

The environment variables are embedded during build time. Since Create Divi Extension produces static CSS/JS bundles, it can’t possibly read them at runtime.

Note: You must create custom environment variables beginning with DIVI_EXTENSION_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

These environment variables will be defined for you on process.env. For example, having an environment variable named DIVI_EXTENSION_SECRET_CODE will be exposed in your JS as process.env.DIVI_EXTENSION_SECRET_CODE.

There is also a special built-in environment variable called NODE_ENV. You can read it from process.env.NODE_ENV. When you run npm start, it is always equal to 'development', when you run npm test it is always equal to 'test', and when you run npm run build to make a production bundle, it is always equal to 'production'. You cannot override NODE_ENV manually. This prevents developers from accidentally deploying a slow development build to production.

These environment variables can be useful for displaying information conditionally based on where the project is deployed or consuming sensitive data that lives outside of version control.

First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined in the environment inside a <form>:

render() {
  return (
    <div>
      <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small>
      <form>
        <input type="hidden" defaultValue={process.env.DIVI_EXTENSION_SECRET_CODE} />
      </form>
    </div>
  );
}

During the build, process.env.DIVI_EXTENSION_SECRET_CODE will be replaced with the current value of the DIVI_EXTENSION_SECRET_CODE environment variable. Remember that the NODE_ENV variable will be set for you automatically.

When you load the extension in the browser and inspect the <input>, you will see its value set to abcdef, and the bold text will show the environment provided when using npm start:

<div>
  <small>You are running this application in <b>development</b> mode.</small>
  <form>
    <input type="hidden" value="abcdef" />
  </form>
</div>

The above form is looking for a variable called DIVI_EXTENSION_SECRET_CODE from the environment. In order to consume this value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in a .env file. Both of these ways are described in the next few sections.

Having access to the NODE_ENV is also useful for performing actions conditionally:

if (process.env.NODE_ENV !== 'production') {
  analytics.disable();
}

When you compile the extension with npm run build, the minification step will strip out this condition, and the resulting bundle will be smaller.

Adding Temporary Environment Variables In Your Shell

Defining environment variables can vary between OSes. It’s also important to know that this is temporary for the life of the shell session.

Windows (cmd.exe)

set "DIVI_EXTENSION_SECRET_CODE=abcdef" && npm start

(Note: Quotes around the variable assignment are required to avoid a trailing whitespace.)

Windows (Powershell)

($env:DIVI_EXTENSION_SECRET_CODE = "abcdef") -and (npm start)

Linux, macOS (Bash)

DIVI_EXTENSION_SECRET_CODE=abcdef npm start

Adding Development Environment Variables In .env

To define permanent environment variables, create a file called .env in the root of your project:

DIVI_EXTENSION_SECRET_CODE=abcdef

Note: You must create custom environment variables beginning with DIVI_EXTENSION_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

.env files should be checked into source control (with the exclusion of .env*.local).

What other .env files can be used?

  • .env: Default.
  • .env.local: Local overrides. This file is loaded for all environments except test.
  • .env.development, .env.test, .env.production: Environment-specific settings.
  • .env.development.local, .env.test.local, .env.production.local: Local overrides of environment-specific settings.

Files on the left have more priority than files on the right:

  • npm start: .env.development.local, .env.development, .env.local, .env
  • npm run build: .env.production.local, .env.production, .env.local, .env
  • npm test: .env.test.local, .env.test, .env (note .env.local is missing)

These variables will act as the defaults if the machine does not explicitly set them.
Please refer to the dotenv documentation for more details.

Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need these defined as well. Consult their documentation how to do this. For example, see the documentation for Travis CI or Heroku.

Expanding Environment Variables In .env

Expand variables already on your machine for use in your .env file (using dotenv-expand).

For example, to get the environment variable npm_package_version:

DIVI_EXTENSION_VERSION=$npm_package_version
# also works:
# DIVI_EXTENSION_VERSION=${npm_package_version}

Or expand variables local to the current .env file:

DOMAIN=www.example.com
DIVI_EXTENSION_FOO=$DOMAIN/foo
DIVI_EXTENSION_BAR=$DOMAIN/bar

Can I Use Decorators?

Many popular libraries use decorators in their documentation.
Create Divi Extension doesn’t support decorator syntax at the moment because:

  • It is an experimental proposal and is subject to change.
  • The current specification version is not officially supported by Babel.
  • If the specification changes, Facebook won’t be able to write a codemod because they don’t use them internally.

However in many cases you can rewrite decorator-based code without decorators just as fine.
Please refer to these two threads for reference:

Create Divi Extension will add decorator support when the specification advances to a stable stage.

Fetching Data with AJAX Requests

React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like axios or the fetch() API provided by the browser. Conveniently, Create Divi Extension includes a polyfill for fetch() so you can use it without worrying about the browser support.

The global fetch function allows you to easily make AJAX requests. It takes in a URL as an input and returns a Promise that resolves to a Response object. You can find more information about fetch here.

This project also includes a Promise polyfill which provides a full implementation of Promises/A+. A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises here and here. Both axios and fetch() use Promises under the hood. You can also use the async / await syntax to reduce the callback nesting.

You can learn more about making AJAX requests from React components in the FAQ entry on the React website.

Advanced Configuration

You can adjust various development and production settings by setting environment variables in your shell or with .env.

Variable Development Production Usage
BROWSER By default, Create Divi Extension will open the default system browser, favoring Chrome on macOS. Specify a browser to override this behavior, or set it to none to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to npm start will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the .js extension.
HOST By default, the development web server binds to localhost. You may use this variable to specify a different host.
PORT By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port.
HTTPS When set to true, Create Divi Extension will run the development server in https mode.
PUBLIC_URL Create Divi Extension assumes your application is hosted at the serving web server's root or a subpath as specified in package.json (homepage). Normally, Create Divi Extension ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.
CI 🔶 When set to true, Create Divi Extension treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default.
REACT_EDITOR When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create Divi Extension will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can send a pull request to detect your editor of choice. Setting this environment variable overrides the automatic detection. If you do it, make sure your systems PATH environment variable points to your editor’s bin folder. You can also set it to none to disable it completely.
CHOKIDAR_USEPOLLING When set to true, the watcher runs in polling mode, as necessary inside a VM. Use this option if npm start isn't detecting changes.
GENERATE_SOURCEMAP When set to false, source maps are not generated for a production build. This solves OOM issues on some smaller machines.
NODE_PATH Same as NODE_PATH in Node.js, but only relative folders are allowed. Can be handy for emulating a monorepo setup by setting NODE_PATH=src.

Troubleshooting

yarn start doesn’t detect changes

When you save a file while yarn start is running, the browser should refresh with the updated code.
If this doesn’t happen, try one of the following workarounds:

  • If your project is in a Dropbox folder, try moving it out.
  • If the watcher doesn’t see a file called index.js and you’re referencing it by the folder name, you need to restart the watcher due to a Webpack bug.
  • Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in “Adjusting Your Text Editor”.
  • If your project path contains parentheses, try moving the project to a path without them. This is caused by a Webpack watcher bug.
  • On Linux and macOS, you might need to tweak system settings to allow more watchers.
  • If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an .env file in your project directory if it doesn’t exist, and add CHOKIDAR_USEPOLLING=true to it. This ensures that the next time you run npm start, the watcher uses the polling mode, as necessary inside a VM.

If none of these solutions help please leave a comment in this thread.

yarn build exits too early

It is reported that yarn build can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:

The build failed because the process exited too early. This probably means the system ran out of memory or someone called kill -9 on the process.

If you are completely sure that you didn't terminate the process, consider adding some swap space to the machine you’re building on, or build the project locally.

Moment.js locales are missing

If you use a Moment.js, you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of all the locales provided by Moment.js.

To add a specific Moment.js locale to your bundle, you need to import it explicitly.
For example:

import moment from 'moment';
import 'moment/locale/fr';

If import multiple locales this way, you can later switch between them by calling moment.locale() with the locale name:

import moment from 'moment';
import 'moment/locale/fr';
import 'moment/locale/es';

// ...

moment.locale('fr');

This will only work for locales that have been explicitly imported before.

yarn build fails to minify

Some third-party packages don't compile their code to ES5 before publishing to npm. This often causes problems in the ecosystem because neither browsers (except for most modern versions) nor some tools currently support all ES6 features. We recommend to publish code on npm as ES5 at least for a few more years.


To resolve this:
  1. Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled.
  • Note: Create Divi Extension can consume both CommonJS and ES modules. For Node.js compatibility, it is recommended that the main entry point is CommonJS. However, they can optionally provide an ES module entry point with the module field in package.json. Note that even if a library provides an ES Modules version, it should still precompile other ES6 features to ES5 if it intends to support older browsers.
  1. Fork the package and publish a corrected version yourself.

  2. If the dependency is small enough, copy it to your src/ folder and treat it as application code.

In the future, we might start automatically compiling incompatible third-party modules, but it is not currently supported. This approach would also slow down the production builds.

Alternatives to Ejecting

Ejecting lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to fork divi-scripts and any other packages you need. This article dives into how to do it in depth. You can find more discussion in this issue.

Something Missing?

If you have ideas for more “How To” recipes that should be on this page, let us know or contribute some!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published