@aarondewes/wp-scripts 中文文档教程

发布于 3年前 浏览 63 项目主页 更新于 3年前

Scripts

这是一组为 WordPress 开发量身定制的可重用脚本。 为方便起见,此软件包中提供的每个工具都带有一个集成的推荐配置。

无缝工作时,复杂的命令行界面有助于将项目工作变成更愉快的体验。 然而,认为开发人员可以轻松地首先选择合适的工具,然后确保它们相互配合,包括它们的所有扩展,这是一个误导性的假设。 此外,这还不够,因为开发人员需要自己保持所有配置和相关工具的最新状态。 当他们支持共享相同设置的多个项目时,这个问题会成倍增加。

幸运的是,有一种模式可以简化维护者的生活——可重用脚本。 这个想法归结为将所有必要的配置和脚本移动到一个单一的工具依赖项中。 在大多数情况下,应该可以使用默认设置完成所有任务,但也允许进行一些自定义设置。 有了所有这些,更新所有项目应该成为一项非常简单的任务。

这个包的灵感来自 react-scriptskcd-scripts

Installation

你只需要安装一个npm模块:

npm install @wordpress/scripts --save-dev

注意:这个包需要Node.js 12.0.0或者更高版本,以及 npm 6.9.0 或更高版本。 它与旧版本不兼容。

Setup

这个包提供了一个命令行界面并公开了一个名为 wp-scripts 的二进制文件,因此您可以使用 npx 直接调用它——一个 npm 包运行程序。 但是,此模块旨在使用您项目的 package.json 文件中的 scripts 部分进行配置。 这个综合示例展示了其中包含的大部分功能。

示例:

{
    "scripts": {
        "build": "wp-scripts build",
        "check-engines": "wp-scripts check-engines",
        "check-licenses": "wp-scripts check-licenses",
        "format": "wp-scripts format",
        "lint:css": "wp-scripts lint-style",
        "lint:js": "wp-scripts lint-js",
        "lint:md:docs": "wp-scripts lint-md-docs",
        "lint:md:js": "wp-scripts lint-md-js",
        "lint:pkg-json": "wp-scripts lint-pkg-json",
        "packages-update": "wp-scripts packages-update",
        "start": "wp-scripts start",
        "test:e2e": "wp-scripts test-e2e",
        "test:unit": "wp-scripts test-unit-js"
    }
}

熟悉 JavaScript 构建设置教程可能也是个好主意 用于设置开发环境以使用 ESNext 语法。 它对如何使用 buildstart 脚本进行了非常深入的解释。

Updating to New Release

要将现有项目更新为新版本的 @wordpress/scripts,请打开 changelog,找到您当前使用的版本(检查项目顶级目录中的 package.json),并应用更新版本的迁移说明.

在大多数情况下,在 package.json 中修改 @wordpress/scripts 版本并在项目的根文件夹中运行 npm install 应该就足够了,但最好检查 变更日志 以了解潜在的重大变更。 此软件包中还包含 packages-update 脚本,旨在自动化更新项目中 WordPress 依赖项的过程。

我们承诺将重大更改保持在最低限度,以便您可以尽可能无缝地升级 @wordpress/scripts

Available Scripts

build

根据提供的配置转换您的代码,以便为生产做好准备并针对最佳性能进行优化。 项目代码的入口点应位于 src/index.js 中。 生成的输出将写入 build/index.js。 此脚本在生成单个构建后退出。 对于更适合开发的增量构建,请参阅 start 脚本。

示例:

{
    "scripts": {
        "build": "wp-scripts build",
        "build:custom": "wp-scripts build entry-one.js entry-two.js --output-path=custom"
    }
}

这就是您使用提供的设置执行脚本的方式:

  • npm run build - builds the code for production.
  • npm run build:custom - builds the code for production with two entry points and a custom output folder. Paths for custom entry points are relative to the project root.

该脚本自动使用优化的配置,但有时您可能想要指定一些自定义选项:

  • --webpack-no-externals – disables scripts' assets generation, and omits the list of default externals.
  • --webpack-bundle-analyzer – enables visualization for the size of webpack output files with an interactive zoomable treemap.

Advanced information

该脚本使用 webpack 在幕后。 它会在你的包的顶级目录中寻找 webpack 配置,如果找到就会使用它。 如果没有找到,它将使用 @wordpress/scripts 包提供的默认配置。 在高级用法部分了解更多信息。

check-engines

检查当前的 nodenpm(或 yarn)版本是否匹配给定的 语义版本范围。 如果不满足给定的版本,则打印有关安装所需版本的信息,程序退出并显示错误代码。

示例:

{
    "scripts": {
        "check-engines": "wp-scripts check-engines"
    }
}

这就是您使用提供的设置执行脚本的方式:

  • npm run check-engines - checks installed version of node and npm.

Advanced information

它使用 check-node-版本 幕后提供的推荐配置。 默认要求设置为与此包的 安装 部分中列出的相同 Node.js 和 npm 版本。 您可以按照 check-node-version 文档 中的描述指定您自己的范围。 在高级用法部分了解更多信息。

check-licenses

验证项目的所有依赖项是否与项目自己的许可证兼容。

示例:

{
    "scripts": {
        "check-licenses": "wp-scripts check-licenses --prod --gpl2 --ignore=abab"
    }
}

标志

  • --prod (or --production): When present, validates only dependencies and not devDependencies
  • --dev (or --development): When present, validates only devDependencies and not dependencies
  • --gpl2: Validates against GPLv2 license compatibility
  • --ignore=a,b,c: A comma-separated set of package names to ignore for validation. This is intended to be used primarily in cases where a dependency’s license field is malformed. It’s assumed that any ignored package argument would be manually vetted for compatibility by the project owner.

format

通过以一致的方式格式化源代码,它有助于为您的文件(JavaScript、YAML)实施编码风格准则。

示例:

{
    "scripts": {
        "format": "wp-scripts format",
        "format:src": "wp-scripts format ./src"
    }
}

这就是您使用提供的设置执行脚本的方式:

  • npm run format - formats files in the entire project’s directories.
  • npm run format:src - formats files in the project’s src subfolder’s directories.

当您运行类似于上述 npm run format:src 示例的命令时,您可以提供一个文件、一个目录, 或 glob 语法或它们的任意组合。

默认情况下,位于 buildnode_modulesvendor 文件夹中的文件将被忽略。 您可以通过将忽略文件和目录添加到项目中的 .prettierignore 文件来自定义忽略文件和目录的列表。

lint-js

帮助执行 JavaScript 文件的编码风格指南。

示例:

{
    "scripts": {
        "lint:js": "wp-scripts lint-js",
        "lint:js:src": "wp-scripts lint-js ./src"
    }
}

这就是您使用提供的设置执行脚本的方式:

  • npm run lint:js - lints JavaScript files in the entire project’s directories.
  • npm run lint:js:src - lints JavaScript files in the project’s src subfolder’s directories.

当您运行类似于上面的 npm run lint:js:src 示例的命令时,您可以提供一个文件,目录或 glob 语法或它们的任意组合。 请参阅更多示例

默认情况下,位于 buildnode_modulesvendor 文件夹中的文件将被忽略。

Advanced information

它使用 eslint@wordpress/eslint-plugin npm 包。 您可以使用自己的规则覆盖默认规则,如 eslint 文档 中所述。 在高级用法部分了解更多信息。

lint-pkg-json

帮助执行 package.json 文件的标准。

示例:

{
    "scripts": {
        "lint:pkg-json": "wp-scripts lint-pkg-json",
        "lint:pkg-json:src": "wp-scripts lint-pkg-json ./src"
    }
}

这就是您使用提供的设置执行这些脚本的方式:

  • npm run lint:pkg-json - lints package.json file in the entire project’s directories.
  • npm run lint:pkg-json:src - lints package.json file in the project’s src subfolder’s directories.

当您运行类似于上述 npm run lint:pkg-json:src 示例的命令时,您可以提供也可以扫描一个或多个目录。 请参阅更多示例

默认情况下,位于 buildnode_modulesvendor 文件夹中的文件将被忽略。

Advanced information

它使用 npm-package-json-lint@wordpress/npm-package-json-lint-config npm 包。 您可以使用自己的规则覆盖默认规则,如 npm-package-json-lint wiki 中所述。 在高级用法部分了解更多信息。

lint-md-docs

使用 markdownlint 对 markdown 文件的标记进行 lint 以执行标准。

示例:

{
    "scripts": {
        "lint:md:docs": "wp-scripts lint-md-docs"
    }
}

这是您使用提供的设置执行脚本的方式:

  • npm run lint:md:docs - lints markdown files in the entire project’s directories.

默认情况下,文件位于 buildnode_modulesvendor< /code> 文件夹被忽略。

Advanced information

它使用 markdownlint.markdownlint.json 配置。 此配置调整 linting 规则以匹配 WordPress 标准,您可以使用自己的配置覆盖,请参阅 markdownlint-cli 命令-行参数。

lint-md-js

使用 ESLint 对 markdown 文件中包含的源代码进行 lint 以强制执行 JS 代码标准。

示例:

{
    "scripts": {
        "lint:md:js": "wp-scripts lint-md-js"
    }
}

这是您使用提供的设置执行脚本的方式:

  • npm run lint:md:js - lints markdown files in the entire project’s directories.

默认情况下,文件位于 buildnode_modulesvendor< /code> 文件夹被忽略。

Advanced information

它使用 eslint-plugin-markdown.eslintrc-md.js 配置。 此配置调低了 linting 规则,因为文档通常只包含代码片段。 建议使用 markdown linting 作为检查,但不一定是阻止程序,因为它可能会报告更多错误。

lint-style

帮助为您的样式文件执行编码样式准则。

示例:

{
    "scripts": {
        "lint:style": "wp-scripts lint-style",
        "lint:css:src": "wp-scripts lint-style 'src/**/*.css'"
    }
}

这就是您使用提供的设置执行脚本的方式:

  • npm run lint:style - lints CSS and SCSS files in the entire project’s directories.
  • npm run lint:css:src - lints only CSS files in the project’s src subfolder’s directories.

当您运行类似于上述 npm run lint:css:src 示例的命令时,请务必包含引号文件 glob 周围的标记。 这确保您可以使用 globby 的功能(如 ** globstar),而不管您的 shell . 请参阅更多示例

默认情况下,位于 buildnode_modulesvendor 文件夹中的文件将被忽略。

Advanced information

它使用 stylelint@wordpress/stylelint-config 根据 WordPress CSS 编码标准配置。 您可以使用自己的规则覆盖它们,如 stylelint 用户指南 中所述。 在高级用法部分了解更多信息。

packages-update

将项目中使用的 WordPress 包更新到最新版本。

示例:

{
    "scripts": {
        "packages-update": "wp-scripts packages-update",
        "postpackages-update": "npm run build"
    }
}

Advanced information

该命令通过读取package.json文件检查项目中使用了哪些名称以@wordpress/开头的包,然后执行npm install @ wordpress/package1@latest @wordpress/package2@latest ... --save 将包版本更改为最新版本。

start

根据提供的配置转换您的代码,以便为开发做好准备。 如果您更改代码,脚本将自动重建,您将在控制台中看到构建错误。 项目代码的入口点应位于 src/index.js 中。 生成的输出将写入 build/index.js。 对于更适合生产的单个构建,请参阅 build 脚本。

示例:

{
    "scripts": {
        "start": "wp-scripts start",
        "start:custom": "wp-scripts start entry-one.js entry-two.js --output-path=custom"
    }
}

这就是您使用提供的设置执行脚本的方式:

  • npm start - starts the build for development.
  • npm run start:custom - starts the build for development which contains two entry points and a custom output folder. Paths for custom entry points are relative to the project root.

该脚本自动使用优化的配置,但有时您可能想要指定一些自定义选项:

  • --webpack-no-externals – disables scripts' assets generation, and omits the list of default externals.
  • --webpack-bundle-analyzer – enables visualization for the size of webpack output files with an interactive zoomable treemap.
  • --webpack--devtool – controls how source maps are generated. See options at https://webpack.js.org/configuration/devtool/#devtool.

Advanced information

该脚本使用 webpack 在幕后。 它会在你的包的顶级目录中寻找 webpack 配置,如果找到就会使用它。 如果没有找到,它将使用 @wordpress/scripts 包提供的默认配置。 在高级用法部分了解更多信息。

test-e2e

启动端到端 (E2E) 测试运行器。 可以使用 Jest API 结合 Puppeteer API

Jest 是一个令人愉快的 JavaScript 测试框架,具有专注于简单。

Puppeteer 是一个 Node 库,它提供了一个高级 API 来通过 DevTools 协议。 Puppeteer 默认运行 headless,但可以配置为完整运行(非无头)铬或铬。

示例:

{
    "scripts": {
        "test:e2e": "wp-scripts test-e2e",
        "test:e2e:help": "wp-scripts test-e2e --help",
        "test:e2e:debug": "wp-scripts --inspect-brk test-e2e --puppeteer-devtools"
    }
}

这就是您使用提供的设置执行这些脚本的方式:

  • npm run test:e2e - runs all e2e tests.
  • npm run test:e2e:help - prints all available options to configure e2e test runner.
  • npm run test-e2e -- --puppeteer-interactive - runs all e2e tests interactively.
  • npm run test-e2e FILE_NAME -- --puppeteer-interactive - runs one test file interactively.
  • npm run test-e2e:watch -- --puppeteer-interactive - runs all tests interactively and watch for changes.
  • npm run test-e2e:debug - runs all tests interactively and enables debugging tests.

Jest 将查找具有以下任何流行命名约定的测试文件:

  • Files with .js (or .ts) suffix at any level of depth in spec folders.
  • Files with .spec.js (or .spec.ts) suffix.

该脚本自动检测启动 Puppeteer 的最佳配置,但有时您可能需要指定自定义选项:

  • You can add a jest-puppeteer.config.js at the root of the project or define a custom path using JEST_PUPPETEER_CONFIG environment variable. Check jest-puppeteer for more details.

我们使用 --runInBand Jest CLI 选项强制所有测试在当前进程中连续运行以避免由于它们共享相同的 WordPress 实例而导致的测试之间的冲突。

Advanced information

它在幕后使用 Jest,您可以使用它的所有 CLI 选项。 您还可以运行 ./node_modules/.bin/wp-scripts test:e2e --helpnpm run test:e2e:help (如上所述)来查看所有的可用选项。 在高级用法部分了解更多信息。

如果在任何情况下您想提供自己的 Jest 配置,您都可以这样做。

  • the command receives a --config argument. Example: wp-scripts test-e2e --config my-jest-config.js.
  • there is a file called jest-e2e.config.js, jest-e2e.config.json, jest.config.js, or jest.config.json in the top-level directory of your package (at the same level than your package.json).
  • a jest object can be provided in the package.json file with the test configuration.

test-unit-js

别名test-unit-jest

启动单元测试运行器。 可以使用 Jest API 编写测试。

示例:

{
    "scripts": {
        "test:unit": "wp-scripts test-unit-js",
        "test:unit:help": "wp-scripts test-unit-js --help",
        "test:unit:watch": "wp-scripts test-unit-js --watch",
        "test:unit:debug": "wp-scripts --inspect-brk test-unit-js --runInBand --no-cache"
    }
}

这就是您使用提供的设置执行这些脚本的方式:

  • npm run test:unit - runs all unit tests.
  • npm run test:unit:help - prints all available options to configure unit tests runner.
  • npm run test:unit:watch - runs all unit tests in the watch mode.
  • npm run test:unit:debug - runs all unit tests in debug mode.

Jest 将查找具有以下任何流行命名约定的测试文件:

  • Files with .js (or .ts) suffix located at any level of depth in __tests__ folders.
  • Files with .js (or .ts) suffix directly located in test folders.
  • Files with .test.js (or .test.ts) suffix.

Advanced information

它使用 Jest 在幕后,您可以使用它的所有 CLI 选项。 您还可以运行 ./node_modules/.bin/wp-scripts test:unit --helpnpm run test:unit:help (如上所述)来查看所有的可用选项。 默认情况下,它使用 @wordpress/jest-preset-default npm 包。 您可以使用自己的选项覆盖它们,如 Jest 文档 中所述。 在高级用法部分了解更多信息。

如果在任何情况下您想提供自己的 Jest 配置,您都可以这样做。

  • the command receives a --config argument. Example: wp-scripts test-unit --config my-jest-config.js.
  • there is a file called jest-unit.config.js, jest-unit.config.json, jest.config.js, or jest.config.json in the top-level directory of your package (at the same level than your package.json).
  • a jest object can be provided in the package.json file with the test configuration.

Passing Node.js options

wp-scripts 支持完整的 Node.js CLI 选项。 它们可以在 wp-scripts 命令之后和脚本名称之前传递。

wp-scripts [NODE_OPTIONS] script

Debugging tests

传递 Node.js 选项的一个常见用例是调试测试。

任何支持 Chrome DevTools 协议

按照使用您最喜欢的受支持浏览器或 IDE 调试 Node.js 的说明进行操作。 当说明使用 node --inspect script.jsnode --inspect-brk script.js 时,只需使用 wp-scripts --inspect scriptwp-scripts --inspect-brk script 代替。

下面以 Google Chrome 和 Visual Studio Code 为例。

Debugging in Google Chrome

debugger; 语句放在任何测试中并运行 wp-scripts --inspect-brk test-unit-js --runInBand --no-cache (或 npm从上面运行 test:unit:debug)。

然后在 Google Chrome 中打开 about:inspect 并在您的进程中选择 inspect

将在脚本的第一行设置一个断点(这样做是为了让您有时间打开开发人员工具并防止 Jest 在您有时间执行之前执行)。 单击开发工具右上面板中的恢复按钮继续执行。 当 Jest 执行包含调试器语句的测试时,执行将暂停,您可以检查当前作用域和调用堆栈。

Debugging in Visual Studio Code

version 1.23 可用于调试 Jest 单元测试。

确保 wp-scripts --inspect-brk test-unit-js --runInBand --no-cache 在你的 中保存为 test:unit:debug package.json 文件以在 Visual Studio Code 中运行测试。

调试时,通过单击编辑器左边距中行号旁边的一行,在测试中设置断点。

然后在资源管理器中打开 npm 脚本或在命令面板中运行 Explorer: Focus on NPM Scripts View 以查看 npm 脚本。 要开始测试,请单击 test:unit:debug 旁边的调试图标。

测试将开始运行,执行将在您选择的行暂停,以便您可以在编辑器中检查当前范围和调用堆栈。

有关使用 Visual Studio Code 调试器的更多详细信息,请参阅在 Visual Studio Code 中调试

Debugging e2e tests

由于 e2e 测试同时在节点上下文 (通常是无头的)浏览器上下文中运行,因此并非所有代码行都可以在检查器客户端中设置断点——只有节点上下文在检查器客户端中进行调试。

在节点上下文中执行的代码包括所有测试文件不包括 page.evaluate 函数中的代码。 page.evaluate 函数和其余应用代码在浏览器上下文中执行。

测试代码(node context)可以按照上面的说明正常调试。

要同时调试浏览器上下文,请运行 wp-scripts --inspect-brk test-e2e --puppeteer-devtools--puppeteer-devtools 选项(或 PUPPETEER_DEVTOOLS="true" 环境变量,当与 PUPPETEER_HEADLESS="false" 一起使用时)将禁用 headless模式并在开发工具已经打开的情况下启动浏览器。 然后可以使用这些开发工具在浏览器上下文中设置断点。

如需更多端到端调试技巧,请查看 Puppeteer 调试文档

Advanced Usage

一般来说,这个包应该与一组推荐的配置文件一起使用。 虽然可以覆盖提供的每个配置文件,但如果您必须这样做,则意味着您的用例比预期的要复杂得多。 如果发生这种情况,最好避免使用整个抽象层并设置您的项目以完全控制所使用的工具。

Working with build scripts

buildstart 命令在后台使用 webpack。 webpack 是一种工具,可帮助您将代码转换为其他内容。 例如:它可以采用用 ESNext 编写的代码并输出为生产而缩小的 ES5 兼容代码。

Default webpack config

@wordpress/scripts 捆绑了 WordPress 编辑器用作基础的默认 webpack 配置。 这些是默认设置:

Using CSS

示例:

// index.scss
$body-color: red;

.wp-block-my-block {
    color: $body-color;
}
/* style.css */
.wp-block-my-block {
    background-color: black;
}
// index.js
import './index.scss';
import './style.css';

当您使用默认命令 wp-scripts build(也适用于 start)运行构建时,除了build 文件夹中生成的 JavaScript 文件 index.js,您应该会看到另外两个文件:

  1. index.css – all imported CSS files are bundled into one chunk named after the entry point, which defaults to index.js, and thus the file created becomes index.css. This is for styles used only in the editor.
  2. style-index.css – imported style.css file(s) (applies to SASS and SCSS extensions) get bundled into one style-index.css file that is meant to be used both on the front-end and in the editor.

您还可以有多个入口点,如脚本文档中所述:

wp-scripts start entry-one.js entry-two.js --output-path=custom

如果你这样做,那么生成的 CSS 文件将遵循入口点的名称:entry-one.cssentry-two.css

避免在入口点名称中使用 style 关键字,这可能会破坏您的构建过程。

您还可以通过将 .module 作为扩展名的前缀来捆绑 CSS 模块,例如 style.module.scss。 否则,这些文件的处理方式与所有其他 style.scss 相同。 它们也将被提取到 style-index.css 中。

Using fonts and images

可以引用字体(woffwoff2eotttfotf) 和图像(bmppngjpgjpeggif)如上一节所述,来自 webpack 控制的 CSS 文件。

示例:

/* style.css */
@font-face {
    font-family: Gilbert;
    src: url( ../assets/gilbert-color.otf );
}
.wp-block-my-block {
    background-color: url( ../assets/block-background.png );
    font-family: Gilbert;
}

Using SVG

示例:

import starUrl, { ReactComponent as Star } from './star.svg';

const App = () => (
    <div>
        <img src={ starUrl } alt="star" />
        <Star />
    </div>
);

Provide your own webpack config

如果在任何情况下您想提供自己的 webpack 配置,您都可以这样做。 buildstart 命令将在以下情况下使用您提供的文件:

  • the command receives a --config argument. Example: wp-scripts build --config my-own-webpack-config.js.
  • there is a file called webpack.config.js or webpack.config.babel.js in the top-level directory of your project (at the same level as package.json).
Extending the webpack config

要扩展提供的 webpack 配置,或替换提供的 webpack 配置中的子部分,您可以提供自己的 webpack.config.js 文件,require 提供的 webpack.config.js 文件,并使用 spread operator 导入全部或部分提供的配置。

在下面的示例中,一个 webpack.config.js 文件被添加到根文件夹中,扩展了提供的 webpack 配置,以包含自定义逻辑来解析模块的源代码,并使用 toml。 在没有特定加载器的情况下将 toml 或其他非 JSON 文件导入为 JSON 可能很有用:

const toml = require( 'toml' );
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );

module.exports = {
    ...defaultConfig,
    module: {
        ...defaultConfig.module,
        rules: [
            ...defaultConfig.module.rules,
            {
                test: /.toml/,
                type: 'json',
                parser: {
                    parse: toml.parse,
                },
            },
        ],
    },
};

如果您采用这种方法,请注意此包的未来版本可能会更改我们捆绑的 webpack 和 Babel 插件、默认配置等. 如果需要进行这些更改,它们将在 包的 CHANGELOG 中注册,所以一定要在升级前阅读它。



代码即诗歌。

Scripts

This is a collection of reusable scripts tailored for WordPress development. For convenience, every tool provided in this package comes with an integrated recommended configuration.

When working seamlessly, sophisticated command-line interfaces help to turn work with a project into a more pleasant experience. However, it’s a misleading assumption that developers can easily pick the proper tools in the first place and then ensure that they play along with each other, including all their extensions. Besides, it’s still not enough because developers are left on their own to keep all configurations and dependent tools up to date. This problem multiplies when they support more than one project which shares the same setup.

Fortunately, there is a pattern that can simplify maintainers life – reusable scripts. The idea boils down to moving all the necessary configurations and scripts to one single tool dependency. In most cases, it should be possible to accomplish all tasks using the default settings, but some customization is allowed, too. With all that in place, updating all projects should become a very straightforward task.

This package is inspired by react-scripts and kcd-scripts.

Installation

You only need to install one npm module:

npm install @wordpress/scripts --save-dev

Note: This package requires Node.js 12.0.0 or later, and npm 6.9.0 or later. It is not compatible with older versions.

Setup

This package offers a command-line interface and exposes a binary called wp-scripts so you can call it directly with npx – an npm package runner. However, this module is designed to be configured using the scripts section in the package.json file of your project. This comprehensive example demonstrates the most of the capabilities included.

Example:

{
    "scripts": {
        "build": "wp-scripts build",
        "check-engines": "wp-scripts check-engines",
        "check-licenses": "wp-scripts check-licenses",
        "format": "wp-scripts format",
        "lint:css": "wp-scripts lint-style",
        "lint:js": "wp-scripts lint-js",
        "lint:md:docs": "wp-scripts lint-md-docs",
        "lint:md:js": "wp-scripts lint-md-js",
        "lint:pkg-json": "wp-scripts lint-pkg-json",
        "packages-update": "wp-scripts packages-update",
        "start": "wp-scripts start",
        "test:e2e": "wp-scripts test-e2e",
        "test:unit": "wp-scripts test-unit-js"
    }
}

It might also be a good idea to get familiar with the JavaScript Build Setup tutorial for setting up a development environment to use ESNext syntax. It gives a very in-depth explanation of how to use the build and start scripts.

Updating to New Release

To update an existing project to a new version of @wordpress/scripts, open the changelog, find the version you’re currently on (check package.json in the top-level directory of your project), and apply the migration instructions for the newer versions.

In most cases bumping the @wordpress/scripts version in package.json and running npm install in the root folder of your project should be enough, but it’s good to check the changelog for potential breaking changes. There is also packages-update script included in this package that aims to automate the process of updating WordPress dependencies in your projects.

We commit to keeping the breaking changes minimal so you can upgrade @wordpress/scripts as seamless as possible.

Available Scripts

build

Transforms your code according the configuration provided so it’s ready for production and optimized for the best performance. The entry point for your project’s code should be located in src/index.js. The output generated will be written to build/index.js. This script exits after producing a single build. For incremental builds, better suited for development, see the start script.

Example:

{
    "scripts": {
        "build": "wp-scripts build",
        "build:custom": "wp-scripts build entry-one.js entry-two.js --output-path=custom"
    }
}

This is how you execute the script with presented setup:

  • npm run build - builds the code for production.
  • npm run build:custom - builds the code for production with two entry points and a custom output folder. Paths for custom entry points are relative to the project root.

This script automatically use the optimized config but sometimes you may want to specify some custom options:

  • --webpack-no-externals – disables scripts' assets generation, and omits the list of default externals.
  • --webpack-bundle-analyzer – enables visualization for the size of webpack output files with an interactive zoomable treemap.

Advanced information

This script uses webpack behind the scenes. It’ll look for a webpack config in the top-level directory of your package and will use it if it finds one. If none is found, it’ll use the default config provided by @wordpress/scripts packages. Learn more in the Advanced Usage section.

check-engines

Checks if the current node, npm (or yarn) versions match the given semantic version ranges. If the given version is not satisfied, information about installing the needed version is printed and the program exits with an error code.

Example:

{
    "scripts": {
        "check-engines": "wp-scripts check-engines"
    }
}

This is how you execute the script with presented setup:

  • npm run check-engines - checks installed version of node and npm.

Advanced information

It uses check-node-version behind the scenes with the recommended configuration provided. The default requirements are set to the same Node.js and npm versions as listed in the installation section for this package. You can specify your own ranges as described in check-node-version docs. Learn more in the Advanced Usage section.

check-licenses

Validates that all dependencies of a project are compatible with the project’s own license.

Example:

{
    "scripts": {
        "check-licenses": "wp-scripts check-licenses --prod --gpl2 --ignore=abab"
    }
}

Flags:

  • --prod (or --production): When present, validates only dependencies and not devDependencies
  • --dev (or --development): When present, validates only devDependencies and not dependencies
  • --gpl2: Validates against GPLv2 license compatibility
  • --ignore=a,b,c: A comma-separated set of package names to ignore for validation. This is intended to be used primarily in cases where a dependency’s license field is malformed. It’s assumed that any ignored package argument would be manually vetted for compatibility by the project owner.

format

It helps to enforce coding style guidelines for your files (JavaScript, YAML) by formatting source code in a consistent way.

Example:

{
    "scripts": {
        "format": "wp-scripts format",
        "format:src": "wp-scripts format ./src"
    }
}

This is how you execute the script with presented setup:

  • npm run format - formats files in the entire project’s directories.
  • npm run format:src - formats files in the project’s src subfolder’s directories.

When you run commands similar to the npm run format:src example above, you can provide a file, a directory, or glob syntax or any combination of them.

By default, files located in build, node_modules, and vendor folders are ignored. You can customize the list of ignored files and directories by adding them to a .prettierignore file in your project.

lint-js

Helps enforce coding style guidelines for your JavaScript files.

Example:

{
    "scripts": {
        "lint:js": "wp-scripts lint-js",
        "lint:js:src": "wp-scripts lint-js ./src"
    }
}

This is how you execute the script with presented setup:

  • npm run lint:js - lints JavaScript files in the entire project’s directories.
  • npm run lint:js:src - lints JavaScript files in the project’s src subfolder’s directories.

When you run commands similar to the npm run lint:js:src example above, you can provide a file, a directory, or glob syntax or any combination of them. See more examples.

By default, files located in build, node_modules, and vendor folders are ignored.

Advanced information

It uses eslint with the set of recommended rules defined in @wordpress/eslint-plugin npm package. You can override default rules with your own as described in eslint docs. Learn more in the Advanced Usage section.

lint-pkg-json

Helps enforce standards for your package.json files.

Example:

{
    "scripts": {
        "lint:pkg-json": "wp-scripts lint-pkg-json",
        "lint:pkg-json:src": "wp-scripts lint-pkg-json ./src"
    }
}

This is how you execute those scripts using the presented setup:

  • npm run lint:pkg-json - lints package.json file in the entire project’s directories.
  • npm run lint:pkg-json:src - lints package.json file in the project’s src subfolder’s directories.

When you run commands similar to the npm run lint:pkg-json:src example above, you can provide one or multiple directories to scan as well. See more examples.

By default, files located in build, node_modules, and vendor folders are ignored.

Advanced information

It uses npm-package-json-lint with the set of recommended rules defined in @wordpress/npm-package-json-lint-config npm package. You can override default rules with your own as described in npm-package-json-lint wiki. Learn more in the Advanced Usage section.

lint-md-docs

Uses markdownlint to lint the markup of markdown files to enforce standards.

Example:

{
    "scripts": {
        "lint:md:docs": "wp-scripts lint-md-docs"
    }
}

This is how you execute the script with presented setup:

  • npm run lint:md:docs - lints markdown files in the entire project’s directories.

By default, files located in build, node_modules, and vendor folders are ignored.

Advanced information

It uses markdownlint with the .markdownlint.json configuration. This configuration tunes the linting rules to match WordPress standard, you can override with your own config, see markdownlint-cli for command-line parameters.

lint-md-js

Uses ESLint to lint the source included in markdown files to enforce standards for JS code.

Example:

{
    "scripts": {
        "lint:md:js": "wp-scripts lint-md-js"
    }
}

This is how you execute the script with presented setup:

  • npm run lint:md:js - lints markdown files in the entire project’s directories.

By default, files located in build, node_modules, and vendor folders are ignored.

Advanced information

It uses eslint-plugin-markdown with the .eslintrc-md.js configuration. This configuration tunes down the linting rules since documentation often includes just snippets of code. It is recommended to use the markdown linting as a check, but not necessarily a blocker since it might report more false errors.

lint-style

Helps enforce coding style guidelines for your style files.

Example:

{
    "scripts": {
        "lint:style": "wp-scripts lint-style",
        "lint:css:src": "wp-scripts lint-style 'src/**/*.css'"
    }
}

This is how you execute the script with presented setup:

  • npm run lint:style - lints CSS and SCSS files in the entire project’s directories.
  • npm run lint:css:src - lints only CSS files in the project’s src subfolder’s directories.

When you run commands similar to the npm run lint:css:src example above, be sure to include the quotation marks around file globs. This ensures that you can use the powers of globby (like the ** globstar) regardless of your shell. See more examples.

By default, files located in build, node_modules, and vendor folders are ignored.

Advanced information

It uses stylelint with the @wordpress/stylelint-config configuration per the WordPress CSS Coding Standards. You can override them with your own rules as described in stylelint user guide. Learn more in the Advanced Usage section.

packages-update

Updates the WordPress packages used in the project to their latest version.

Example:

{
    "scripts": {
        "packages-update": "wp-scripts packages-update",
        "postpackages-update": "npm run build"
    }
}

Advanced information

The command checks which packages whose name starts with @wordpress/ are used in the project by reading the package.json file, and then executes npm install @wordpress/package1@latest @wordpress/package2@latest ... --save to change the package versions to the latest one.

start

Transforms your code according the configuration provided so it’s ready for development. The script will automatically rebuild if you make changes to the code, and you will see the build errors in the console. The entry point for your project’s code should be located in src/index.js. The output generated will be written to build/index.js. For single builds, better suited for production, see the build script.

Example:

{
    "scripts": {
        "start": "wp-scripts start",
        "start:custom": "wp-scripts start entry-one.js entry-two.js --output-path=custom"
    }
}

This is how you execute the script with presented setup:

  • npm start - starts the build for development.
  • npm run start:custom - starts the build for development which contains two entry points and a custom output folder. Paths for custom entry points are relative to the project root.

This script automatically use the optimized config but sometimes you may want to specify some custom options:

  • --webpack-no-externals – disables scripts' assets generation, and omits the list of default externals.
  • --webpack-bundle-analyzer – enables visualization for the size of webpack output files with an interactive zoomable treemap.
  • --webpack--devtool – controls how source maps are generated. See options at https://webpack.js.org/configuration/devtool/#devtool.

Advanced information

This script uses webpack behind the scenes. It’ll look for a webpack config in the top-level directory of your package and will use it if it finds one. If none is found, it’ll use the default config provided by @wordpress/scripts packages. Learn more in the Advanced Usage section.

test-e2e

Launches the End-To-End (E2E) test runner. Writing tests can be done using the Jest API in combination with the Puppeteer API:

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.

Example:

{
    "scripts": {
        "test:e2e": "wp-scripts test-e2e",
        "test:e2e:help": "wp-scripts test-e2e --help",
        "test:e2e:debug": "wp-scripts --inspect-brk test-e2e --puppeteer-devtools"
    }
}

This is how you execute those scripts using the presented setup:

  • npm run test:e2e - runs all e2e tests.
  • npm run test:e2e:help - prints all available options to configure e2e test runner.
  • npm run test-e2e -- --puppeteer-interactive - runs all e2e tests interactively.
  • npm run test-e2e FILE_NAME -- --puppeteer-interactive - runs one test file interactively.
  • npm run test-e2e:watch -- --puppeteer-interactive - runs all tests interactively and watch for changes.
  • npm run test-e2e:debug - runs all tests interactively and enables debugging tests.

Jest will look for test files with any of the following popular naming conventions:

  • Files with .js (or .ts) suffix at any level of depth in spec folders.
  • Files with .spec.js (or .spec.ts) suffix.

This script automatically detects the best config to start Puppeteer but sometimes you may need to specify custom options:

  • You can add a jest-puppeteer.config.js at the root of the project or define a custom path using JEST_PUPPETEER_CONFIG environment variable. Check jest-puppeteer for more details.

We enforce that all tests run serially in the current process using --runInBand Jest CLI option to avoid conflicts between tests caused by the fact that they share the same WordPress instance.

Advanced information

It uses Jest behind the scenes and you are able to use all of its CLI options. You can also run ./node_modules/.bin/wp-scripts test:e2e --help or npm run test:e2e:help (as mentioned above) to view all of the available options. Learn more in the Advanced Usage section.

Should there be any situation where you want to provide your own Jest config, you can do so.

  • the command receives a --config argument. Example: wp-scripts test-e2e --config my-jest-config.js.
  • there is a file called jest-e2e.config.js, jest-e2e.config.json, jest.config.js, or jest.config.json in the top-level directory of your package (at the same level than your package.json).
  • a jest object can be provided in the package.json file with the test configuration.

test-unit-js

Alias: test-unit-jest

Launches the unit test runner. Writing tests can be done using the Jest API.

Example:

{
    "scripts": {
        "test:unit": "wp-scripts test-unit-js",
        "test:unit:help": "wp-scripts test-unit-js --help",
        "test:unit:watch": "wp-scripts test-unit-js --watch",
        "test:unit:debug": "wp-scripts --inspect-brk test-unit-js --runInBand --no-cache"
    }
}

This is how you execute those scripts using the presented setup:

  • npm run test:unit - runs all unit tests.
  • npm run test:unit:help - prints all available options to configure unit tests runner.
  • npm run test:unit:watch - runs all unit tests in the watch mode.
  • npm run test:unit:debug - runs all unit tests in debug mode.

Jest will look for test files with any of the following popular naming conventions:

  • Files with .js (or .ts) suffix located at any level of depth in __tests__ folders.
  • Files with .js (or .ts) suffix directly located in test folders.
  • Files with .test.js (or .test.ts) suffix.

Advanced information

It uses Jest behind the scenes and you are able to use all of its CLI options. You can also run ./node_modules/.bin/wp-scripts test:unit --help or npm run test:unit:help (as mentioned above) to view all of the available options. By default, it uses the set of recommended options defined in @wordpress/jest-preset-default npm package. You can override them with your own options as described in Jest documentation. Learn more in the Advanced Usage section.

Should there be any situation where you want to provide your own Jest config, you can do so.

  • the command receives a --config argument. Example: wp-scripts test-unit --config my-jest-config.js.
  • there is a file called jest-unit.config.js, jest-unit.config.json, jest.config.js, or jest.config.json in the top-level directory of your package (at the same level than your package.json).
  • a jest object can be provided in the package.json file with the test configuration.

Passing Node.js options

wp-scripts supports the full array of Node.js CLI options. They can be passed after the wp-scripts command and before the script name.

wp-scripts [NODE_OPTIONS] script

Debugging tests

One common use-case for passing Node.js options is debugging your tests.

Tests can be debugged by any inspector client that supports the Chrome DevTools Protocol.

Follow the instructions for debugging Node.js with your favorite supported browser or IDE. When the instructions say to use node --inspect script.js or node --inspect-brk script.js, simply use wp-scripts --inspect script or wp-scripts --inspect-brk script instead.

Google Chrome and Visual Studio Code are used as examples below.

Debugging in Google Chrome

Place debugger; statements in any test and run wp-scripts --inspect-brk test-unit-js --runInBand --no-cache (or npm run test:unit:debug from above).

Then open about:inspect in Google Chrome and select inspect on your process.

A breakpoint will be set at the first line of the script (this is done to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the resume button in the upper right panel of the dev tools to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.

Debugging in Visual Studio Code

Debugging npm scripts is supported out of the box for Visual Studio Code as of version 1.23 and can be used to debug Jest unit tests.

Make sure wp-scripts --inspect-brk test-unit-js --runInBand --no-cache is saved as test:unit:debug in your package.json file to run tests in Visual Studio Code.

When debugging, set a breakpoint in your tests by clicking on a line in the editor’s left margin by the line numbers.

Then open npm scripts in the explorer or run Explorer: Focus on NPM Scripts View in the command palette to see the npm scripts. To start the tests, click the debug icon next to test:unit:debug.

The tests will start running, and execution will pause on your selected line so you can inspect the current scope and call stack within the editor.

See Debugging in Visual Studio Code for more details on using the Visual Studio Code debugger.

Debugging e2e tests

Since e2e tests run both in the node context and the (usually headless) browser context, not all lines of code can have breakpoints set within the inspector client—only the node context is debugged in the inspector client.

The code executed in the node context includes all of the test files excluding code within page.evaluate functions. The page.evaluate functions and the rest of your app code is executed within the browser context.

Test code (node context) can be debugged normally using the instructions above.

To also debug the browser context, run wp-scripts --inspect-brk test-e2e --puppeteer-devtools. The --puppeteer-devtools option (or the PUPPETEER_DEVTOOLS="true" environment variable when used with PUPPETEER_HEADLESS="false") will disable headless mode and launch the browser with the devtools already open. Breakpoints can then be set in the browser context using these devtools.

For more e2e debugging tips check out the Puppeteer debugging docs.

Advanced Usage

In general, this package should be used with the set of recommended config files. While it’s possible to override every single config file provided, if you have to do it, it means that your use case is far more complicated than anticipated. If that happens, it would be better to avoid using the whole abstraction layer and set up your project with full control over tooling used.

Working with build scripts

The build and start commands use webpack behind the scenes. webpack is a tool that helps you transform your code into something else. For example: it can take code written in ESNext and output ES5 compatible code that is minified for production.

Default webpack config

@wordpress/scripts bundles the default webpack config used as a base by the WordPress editor. These are the defaults:

Using CSS

Example:

// index.scss
$body-color: red;

.wp-block-my-block {
    color: $body-color;
}
/* style.css */
.wp-block-my-block {
    background-color: black;
}
// index.js
import './index.scss';
import './style.css';

When you run the build using the default command wp-scripts build (also applies to start) in addition to the JavaScript file index.js generated in the build folder, you should see two more files:

  1. index.css – all imported CSS files are bundled into one chunk named after the entry point, which defaults to index.js, and thus the file created becomes index.css. This is for styles used only in the editor.
  2. style-index.css – imported style.css file(s) (applies to SASS and SCSS extensions) get bundled into one style-index.css file that is meant to be used both on the front-end and in the editor.

You can also have multiple entry points as described in the docs for the script:

wp-scripts start entry-one.js entry-two.js --output-path=custom

If you do so, then CSS files generated will follow the names of the entry points: entry-one.css and entry-two.css.

Avoid using style keyword in an entry point name, this might break your build process.

You can also bundle CSS modules by prefixing .module to the extension, e.g. style.module.scss. Otherwise, these files are handled like all other style.scss. They will also be extracted into style-index.css.

Using fonts and images

It is possible to reference font (woff, woff2, eot, ttf and otf) and image (bmp, png, jpg, jpeg and gif) files from CSS that is controlled by webpack as explained in the previous section.

Example:

/* style.css */
@font-face {
    font-family: Gilbert;
    src: url( ../assets/gilbert-color.otf );
}
.wp-block-my-block {
    background-color: url( ../assets/block-background.png );
    font-family: Gilbert;
}

Using SVG

Example:

import starUrl, { ReactComponent as Star } from './star.svg';

const App = () => (
    <div>
        <img src={ starUrl } alt="star" />
        <Star />
    </div>
);

Provide your own webpack config

Should there be any situation where you want to provide your own webpack config, you can do so. The build and start commands will use your provided file when:

  • the command receives a --config argument. Example: wp-scripts build --config my-own-webpack-config.js.
  • there is a file called webpack.config.js or webpack.config.babel.js in the top-level directory of your project (at the same level as package.json).
Extending the webpack config

To extend the provided webpack config, or replace subsections within the provided webpack config, you can provide your own webpack.config.js file, require the provided webpack.config.js file, and use the spread operator to import all of or part of the provided configuration.

In the example below, a webpack.config.js file is added to the root folder extending the provided webpack config to include custom logic to parse module's source and convert it to a JavaScript object using toml. It may be useful to import toml or other non-JSON files as JSON, without specific loaders:

const toml = require( 'toml' );
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );

module.exports = {
    ...defaultConfig,
    module: {
        ...defaultConfig.module,
        rules: [
            ...defaultConfig.module.rules,
            {
                test: /.toml/,
                type: 'json',
                parser: {
                    parse: toml.parse,
                },
            },
        ],
    },
};

If you follow this approach, please, be aware that future versions of this package may change what webpack and Babel plugins we bundle, default configs, etc. Should those changes be necessary, they will be registered in the package’s CHANGELOG, so make sure to read it before upgrading.



Code is Poetry.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文