From c9357bf26132fb1b715f35f6ecb0ecb8a73d054d Mon Sep 17 00:00:00 2001 From: Marcus Kazmierczak Date: Thu, 7 Feb 2019 09:49:42 -0800 Subject: [PATCH] Add JavaScript Documentation around setting up Webpack, Babel, and Building (#13629) * Add JS Build Setup * Update docs/designers-developers/developers/tutorials/javascript/js-build-setup.md Co-Authored-By: mkaz * Whitespace and code brackets * Update with better npm install instructions using --save-dev * Update docs/designers-developers/developers/tutorials/javascript/versions-and-building.md Co-Authored-By: mkaz * Update docs/designers-developers/developers/tutorials/javascript/js-build-setup.md Co-Authored-By: mkaz * Updates node, cli, and pragma per review * Update why to use ESNext * Apply suggestions from code review Co-Authored-By: mkaz * Apply suggestions from code review Co-Authored-By: mkaz --- .../tutorials/javascript/js-build-setup.md | 239 ++++++++++++++++++ .../javascript/versions-and-building.md | 5 +- docs/manifest.json | 90 ++++--- docs/toc.json | 17 +- 4 files changed, 299 insertions(+), 52 deletions(-) create mode 100644 docs/designers-developers/developers/tutorials/javascript/js-build-setup.md diff --git a/docs/designers-developers/developers/tutorials/javascript/js-build-setup.md b/docs/designers-developers/developers/tutorials/javascript/js-build-setup.md new file mode 100644 index 0000000000000..916e154de0763 --- /dev/null +++ b/docs/designers-developers/developers/tutorials/javascript/js-build-setup.md @@ -0,0 +1,239 @@ +# JavaScript Build Setup + +This page covers how to set up your development environment to use the ESNext syntax. ESNext is JavaScript code written using features that are only available in a specification greater than ECMAScript 5 (ES5 for short) or that includes a custom syntax such as [JSX](https://reactjs.org/docs/introducing-jsx.html). + +This documentation covers development for your plugin to work with Gutenberg. If you want to setup a development environment for developing Gutenberg itself, see the [CONTRIBUTING.md](https://github.com/WordPress/gutenberg/blob/master/CONTRIBUTING.md) documentation. + +Most browsers can not interpret or run ESNext and JSX syntaxes, so we use a transformation step to convert these syntaxes to code that browsers can understand. + +There are a few reasons to use ESNext and the extra step. First, it makes for simpler code that is easier to read and write. Using a transformation step allows for tools to optimize the code to work on the widest variety of browsers. Also, by using a build step you can organize your code into smaller modules and files that can be bundled together into a single download. + +There are many tools that can perform this transformation or build step, but in this tutorial we will focus on Webpack and Babel. + +[Webpack](https://webpack.js.org/) is a pluggable tool that processes JavaScript creating a compiled bundle that runs in a browser. [Babel](https://babeljs.io/) transforms JavaScript from one format to another. You use Babel as a plugin to Webpack to transform both ESNext and JSX to JavaScript. + +## Quick Start + +For a quick start, you can use one of the examples from the [Gutenberg Examples repository](https://github.com/wordpress/gutenberg-examples/). Each one of the `-esnext` directories contain the necessary files for working with ESNext and JSX. + +## Setup + +Both Webpack and Babel are tools written in JavaScript and run using [Node.js](https://nodejs.org/) (node). Node.js is a runtime environment for JavaScript outside of a browser. Simply put, node allows you to run JavaScript code on the command-line. + +First, you need to set up node for your development environment. The steps required change depending on your operating system, but if you have a package manager installed, setup can be as straightforward as: + +- Ubuntu: `apt install node` +- macOS: `brew install node` +- Windows: `choco install node` + +Additionally, the [Node.js download page](https://nodejs.org/en/download/) includes installers and binaries. + +**Note:** The build tools and process occur on the command-line, so some basic familiarity using a terminal application is required. Some text editors have a terminal built-in which is fine to use; Visual Studio Code and PhpStorm are two popular options. + +### Node Package Manager (npm) + +The Node Package Manager (npm) is a tool included with node. npm allows you to install and manage JavaScript packages. npm can also generate and process a special file called `package.json`, which contains some information about your project and the packages your project uses. + +To start a new node project, first create a directory to work in. + +``` +mkdir myguten-block +``` + +You create a new package.json running `npm init` in your terminal. This will walk you through creating your package.json file: + +``` +npm init + +package name: (myguten-block) myguten-block +version: (1.0.0) +description: Test block +entry point: (index.js) block.js +test command: +git repository: +keywords: +author: mkaz +license: (ISC) GPL-2.0-only +About to write to /home/mkaz/src/wp/scratch/package.json: + +{ + "name": "myguten-block", + "version": "1.0.0", + "description": "Test block", + "main": "block.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "mkaz", + "license": "GPL-2.0-only" +} + + +Is this OK? (yes) yes +``` + +### Using npm to install packages + +The next step is to install the packages required. You can install packages using the npm command `npm install`. If you pass the `--save-dev` parameter, npm will write the package as a dev dependency in the package.json file. + +Run `npm install --save-dev webpack` + +After installing, a `node_modules` directory is created with the webpack module and its dependencies. + +Also, if you look at package.json file it will include a new section: + +```json +"dependencies": { + "webpack": "^4.29.0" +} +``` + +## Webpack & Babel + +Next, we will configure webpack to process the `block.js` file and run babel to transform the JSX within it. + +Create the file `webpack.config.js` + +```js +// sets mode webpack runs under +const NODE_ENV = process.env.NODE_ENV || 'development'; + +module.exports = { + mode: NODE_ENV, + + // entry is the source script + entry: './block.js', + + // output is where to write the built file + output: { + path: __dirname, + filename: 'block.build.js', + }, + module: { + // the list of rules used to process files + // this looks for .js files, exclude files + // in node_modules directory, and uses the + // babel-loader to process + rules: [ + { + test: /.js$/, + exclude: /node_modules/, + loader: 'babel-loader', + }, + ], + }, +}; +``` + +Next, you need to install babel, the webpack loader, and the JSX plugin using: + +``` +npm install --save babel-loader babel-core babel-plugin-transform-react-jsx +``` + +You configure babel by creating a `.babelrc` file: + +``` +{ + "plugins": [ + [ "transform-react-jsx", { + "pragma": "wp.element.createElement" + } ] + ] +} +``` + +This pragma setting instructs Babel that any JSX syntax such as `` should be transformed into `wp.element.createElement( Hello )`. The name of the setting (`transform-react-jsx`) is derived from the fact that it overrides the default assumption to transform to `React.createElement( Hello )`. + +With both configs in place, you can now run webpack. + +First you need a basic block.js to build. Create `block.js` with the following content: + +```js +const { registerBlockType } = wp.blocks; + +registerBlockType( 'myguten/test-block', { + title: 'Basic Example', + icon: 'smiley', + category: 'layout', + edit() { + return
Hola, mundo!
; + }, + save() { + return
Hola, mundo!
; + }, +} ); +``` + +To configure npm to run a script, you use the scripts section in `package.json` webpack: + +```json + "scripts": { + "build": "webpack" + }, +``` + +You can then run the build using: `npm run build`. + +After the build finishes, you will see the built file created at `block.build.js`. + +## Finishing Touches + +### Development Mode + +The basics are in place to build. You might have noticed the webpack.config.js sets a default mode of "development". Webpack can also run in a "production" mode, which shrinks the code down so it downloads faster, but makes it difficult to read. + +The mode is setup so it can be configured using environment variables, which can be added in the scripts section of `package.json`. + +```json + "scripts": { + "dev": "webpack --watch", + "build": "cross-env NODE_ENV=production webpack" + }, +``` + +This sets the environment variables, but different environments handle these settings in different ways. Using the `cross-env` helper module can help to handle this. Be sure to install the `cross-env` package using `npm install --save cross-env`. + +Additionally, webpack has a `--watch` flag that will keep the process running, watching for any changes to the `block.js` file and re-building as changes occur. This is useful during development, when you might have a lot of changes in progress. + +You can start the watcher by running `npm run dev` in a terminal. You can then edit away in your text editor; after each save, webpack will automatically build. You can then use the familiar edit/save/reload development process. + +**Note:** keep an eye on your terminal for any errors. If you make a typo or syntax error, the build will fail and the error will be in the terminal. + +### Babel Browser Targeting + +Babel has the ability to build JavaScript using rules that target certain browsers and versions. By setting a reasonable set of modern browsers, Babel can optimize the JavaScript it generates. + +WordPress has a preset default you can use to target the minimum supported browsers by WordPress. + +Install the module using: `npm install --save @wordpress/babel-preset-default` + +You then update `.babelrc` by adding a "presets" section: + +``` +{ + "presets": [ "@wordpress/babel-preset-default" ], + "plugins": [ + [ "transform-react-jsx", { + "pragma": "wp.element.createElement" + } ] + ] +} +``` + +### Source Control + +Because a typical `node_modules` folder will contain thousands of files that change with every software update, you should exclude `node_modules/` from your source control. If you ever start from a fresh clone, simply run `npm install` in the same folder your `package.json` is located to pull your required packages. + +Likewise, you do not need to include `node_modules` or any of the above configuration files in your plugin because they will be bundled inside the file that webpack builds. **Be sure to enqueue the `block.build.js` file** in your plugin PHP. This is the only JavaScript file needed for your block to run. + +## Summary + +Yes, the initial setup is rather tedious, and there are a number of different tools and configs to learn. However, as the quick start alluded to, copying an existing config is the typical way most people start. + +With a setup in place, the standard workflow is: + +- Install dependencies: `npm install` +- Start development builds: `npm run dev` +- Develop. Test. Repeat. +- Create production build: `npm run build` diff --git a/docs/designers-developers/developers/tutorials/javascript/versions-and-building.md b/docs/designers-developers/developers/tutorials/javascript/versions-and-building.md index fb52d247d7861..416afe6254934 100644 --- a/docs/designers-developers/developers/tutorials/javascript/versions-and-building.md +++ b/docs/designers-developers/developers/tutorials/javascript/versions-and-building.md @@ -6,6 +6,7 @@ ES5 code is compatible with WordPress's minimum [target for browser support](htt "ESNext" doesn't refer to a specific version of JavaScript, but is "dynamic" and refers to the next language definitions, whatever they might be. Because some browsers won't support these features yet (because they're new or proposed), an extra build step is required to transform the code to a syntax that works in all browsers. Webpack and babel are the tools that perform this transformation step. -Additionally, the ESNext code examples in the Gutenberg handbook include [JSX syntax](https://reactjs.org/docs/introducing-jsx.html), a syntax that blends HTML and JavaScript. It makes it easier to read and write markup code, but likewise requires the build step using webpack and babel to transform into compatible code. +Additionally, the ESNext code examples in the Gutenberg handbook include [JSX syntax](https://reactjs.org/docs/introducing-jsx.html), a syntax that blends HTML and JavaScript. It makes it easier to read and write markup code, but likewise requires the build step using Webpack and Babel to transform into compatible code. + +For simplicity, the JavaScript tutorial uses the ES5 definition, without JSX. This code can run straight in your browser and does not require an additional build step. In many cases, it will be perfectly fine to follow the same approach to quickly start experimenting with your plugin or theme. As soon as your codebase grows to hundreds of lines it might be a good idea to get familiar with the [JavaScript Build Setup documentation](/docs/designers-developers/developers/tutorials/javascript/js-build-setup.md) for setting up a development environment to use ESNext syntax. -For simplicity, this tutorial uses the ES5 definition of JavaScript, without JSX. This code can run straight in your browser and does not require an additional build step. diff --git a/docs/manifest.json b/docs/manifest.json index 4e8380c93aaf7..675c7034e52a1 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -161,48 +161,6 @@ "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/readme.md", "parent": "developers" }, - { - "title": "Blocks", - "slug": "block-tutorial", - "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/readme.md", - "parent": "tutorials" - }, - { - "title": "Writing Your First Block Type", - "slug": "writing-your-first-block-type", - "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/writing-your-first-block-type.md", - "parent": "block-tutorial" - }, - { - "title": "Applying Styles From a Stylesheet", - "slug": "applying-styles-with-stylesheets", - "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/applying-styles-with-stylesheets.md", - "parent": "block-tutorial" - }, - { - "title": "Introducing Attributes and Editable Fields", - "slug": "introducing-attributes-and-editable-fields", - "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/introducing-attributes-and-editable-fields.md", - "parent": "block-tutorial" - }, - { - "title": "Block Controls: Toolbars and Inspector", - "slug": "block-controls-toolbars-and-inspector", - "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/block-controls-toolbars-and-inspector.md", - "parent": "block-tutorial" - }, - { - "title": "Creating dynamic blocks", - "slug": "creating-dynamic-blocks", - "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/creating-dynamic-blocks.md", - "parent": "block-tutorial" - }, - { - "title": "Generate Blocks with WP-CLI", - "slug": "generate-blocks-with-wp-cli", - "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/generate-blocks-with-wp-cli.md", - "parent": "block-tutorial" - }, { "title": "Getting Started with JavaScript", "slug": "javascript", @@ -245,6 +203,54 @@ "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/javascript/scope-your-code.md", "parent": "javascript" }, + { + "title": "JavaScript Build Setup", + "slug": "js-build-setup", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/javascript/js-build-setup.md", + "parent": "javascript" + }, + { + "title": "Blocks", + "slug": "block-tutorial", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/readme.md", + "parent": "tutorials" + }, + { + "title": "Writing Your First Block Type", + "slug": "writing-your-first-block-type", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/writing-your-first-block-type.md", + "parent": "block-tutorial" + }, + { + "title": "Applying Styles From a Stylesheet", + "slug": "applying-styles-with-stylesheets", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/applying-styles-with-stylesheets.md", + "parent": "block-tutorial" + }, + { + "title": "Introducing Attributes and Editable Fields", + "slug": "introducing-attributes-and-editable-fields", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/introducing-attributes-and-editable-fields.md", + "parent": "block-tutorial" + }, + { + "title": "Block Controls: Toolbars and Inspector", + "slug": "block-controls-toolbars-and-inspector", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/block-controls-toolbars-and-inspector.md", + "parent": "block-tutorial" + }, + { + "title": "Creating dynamic blocks", + "slug": "creating-dynamic-blocks", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/creating-dynamic-blocks.md", + "parent": "block-tutorial" + }, + { + "title": "Generate Blocks with WP-CLI", + "slug": "generate-blocks-with-wp-cli", + "markdown_source": "https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/developers/tutorials/block-tutorial/generate-blocks-with-wp-cli.md", + "parent": "block-tutorial" + }, { "title": "Meta Boxes", "slug": "metabox", diff --git a/docs/toc.json b/docs/toc.json index cf299daf60c62..d3e7b6048a130 100644 --- a/docs/toc.json +++ b/docs/toc.json @@ -30,6 +30,15 @@ {"docs/designers-developers/developers/backward-compatibility/meta-box.md": []} ]}, {"docs/designers-developers/developers/tutorials/readme.md": [ + {"docs/designers-developers/developers/tutorials/javascript/readme.md": [ + {"docs/designers-developers/developers/tutorials/javascript/plugins-background.md": []}, + {"docs/designers-developers/developers/tutorials/javascript/loading-javascript.md": []}, + {"docs/designers-developers/developers/tutorials/javascript/extending-the-block-editor.md": []}, + {"docs/designers-developers/developers/tutorials/javascript/troubleshooting.md": []}, + {"docs/designers-developers/developers/tutorials/javascript/versions-and-building.md": []}, + {"docs/designers-developers/developers/tutorials/javascript/scope-your-code.md": []}, + {"docs/designers-developers/developers/tutorials/javascript/js-build-setup.md": []} + ]}, {"docs/designers-developers/developers/tutorials/block-tutorial/readme.md" :[ {"docs/designers-developers/developers/tutorials/block-tutorial/writing-your-first-block-type.md" :[]}, {"docs/designers-developers/developers/tutorials/block-tutorial/applying-styles-with-stylesheets.md" :[]}, @@ -38,14 +47,6 @@ {"docs/designers-developers/developers/tutorials/block-tutorial/creating-dynamic-blocks.md" :[]}, {"docs/designers-developers/developers/tutorials/block-tutorial/generate-blocks-with-wp-cli.md" :[]} ]}, - {"docs/designers-developers/developers/tutorials/javascript/readme.md": [ - {"docs/designers-developers/developers/tutorials/javascript/plugins-background.md": []}, - {"docs/designers-developers/developers/tutorials/javascript/loading-javascript.md": []}, - {"docs/designers-developers/developers/tutorials/javascript/extending-the-block-editor.md": []}, - {"docs/designers-developers/developers/tutorials/javascript/troubleshooting.md": []}, - {"docs/designers-developers/developers/tutorials/javascript/versions-and-building.md": []}, - {"docs/designers-developers/developers/tutorials/javascript/scope-your-code.md": []} - ]}, {"docs/designers-developers/developers/tutorials/metabox/readme.md": [ {"docs/designers-developers/developers/tutorials/metabox/meta-block-1-intro.md": []}, {"docs/designers-developers/developers/tutorials/metabox/meta-block-2-register-meta.md": []},