高階WordPress開發:如何使用wp-scripts建立下一個專案

如何使用wp-scripts建立下一個專案

代理公司的 WordPress 開發工作在最好的情況下也會競爭激烈。它要求在多個客戶專案中保持最高的效率和一致性。

無論你是多麼老練的開發人員,管理整個定製主題和外掛的組合仍然需要在簡化工作流程方面付出長期的努力。wp-scripts 是一套功能強大的實用工具,它能徹底改變你的公司對 WordPress 的開發方式。

本綜合指南將介紹 wp-scripts 的功能,並探討構建流程的技巧。在整個過程中,它將涵蓋優化編譯和捆綁、自動內襯、單元測試等內容–如果你同時兼顧多個高風險的 WordPress 專案,那麼所有這些內容都與你息息相關。

構建流程的概念

在瞭解 wp-scripts 的具體細節之前,我們先來了解一下網站開發構建流程的大概念。這包括一系列自動化任務,幫助將原始碼轉化為可投入生產的應用程式或網站。

例如,有很多工作都可以通過這種方式從自動化中獲益:

  • 將現代 JavaScript 編譯成與瀏覽器相容的程式碼。
  • 將 CSS 前處理器語言(例如 Sass)轉換為標準 CSS。
  • 最小化和優化 JavaScript、CSS 和媒體等資產。
  • 執行 linters 以捕捉潛在錯誤並執行編碼標準。
  • 執行單元測試,確保更好的程式碼功能。

對於任何開發工作流程來說,這些都是可以實現自動化的方面,但對於機構來說,這一流程同樣至關重要。首先,您可以在多個專案(和您的團隊)中保持一致性。

您還可以通過更快的週期進行開發和部署,並利用一致性維護所有專案,即使是最複雜的專案也不例外。對於終端使用者而言,您所獲得的優化效能將惠及他們的整體體驗。

通常情況下,您的機構可能會使用 Gulp、Grunt 等工具或甚至手動流程“拼湊”自定義構建流程。然而,這些方法往往會導致專案之間的不一致性,更不用說大量的維護開銷了。

wp-scripts:改變機構內WordPress開發工作流程的工具

就 WordPress 而言,構建流程也可以大大簡化主題和外掛的開發。它可以讓您使用現代工具和實踐,同時確保平臺相容性。

@wordpress/scripts 包(本文中為wp-scripts)是一組配置檔案和指令碼,可幫助您簡化 WordPress 專案的構建流程。

wp-scripts 參考資料

wp-scripts 參考資料的一部分,用於專案將使用的各種指令碼。

Make WordPress 核心團隊負責開發和維護該軟體包,它是塊編輯器和站點編輯器不可或缺的一部分。最重要的是,你還可以用它來定製主題和開發外掛。

對於機構內的大規模 WordPress 開發而言,wp-scripts將是工作流程的核心部分。它不僅僅是一個簡單的構建工具;它是現代 WordPress 專案的全面解決方案,符合複雜開發工作流程的需要。

wp-scripts的關鍵功能

隨著更多現代 JavaScript 實踐滲入 WordPress 生態系統,我們需要更多標準化的構建工具來適應它們。以 wp-scripts 為形式的統一構建工具集有利於整個WordPress開發生態系統。

因此,wp-scripts 提供了一系列功能,使 WordPress 開發更加高效:

  • 零配置設定。您無需進行復雜的 webpack 配置即可開始使用。
  • 現代 JavaScript 支援。您的 ES6 程式碼將轉譯以相容瀏覽器,讓您對程式碼的準確性更有信心。
  • 內建 CSS 處理。如果您使用 CSS 前處理器(如 Sass),您將獲得開箱即用的支援。
  • 程式碼質量工具。軟體包整合了 ESLint 和 Prettier,可確保程式碼風格和質量的一致性。
  • 測試工具。軟體包中的 Jest 可用於單元測試和輕鬆執行。
  • 熱過載。如果能實時過載更改,就能加快開發時間。

綜合來看,wp-scripts 為管理多個 WordPress 專案的機構提供了許多關鍵優勢。例如,您可以將每個專案的開發環境標準化,還可以在任何新專案中複製構建過程。該軟體包可讓您集中構建工具的依賴關係,從而使更新和安全補丁更易於管理。

總之,您可以減少對相容性問題的擔心,縮短設定時間,並消除在簡化構建過程中出現的許多典型錯誤。

將wp-scripts與典型的WordPress開發流程進行比較

典型的WordPress開發通常涉及使用手動排隊來獲取指令碼和樣式。此外,您還可能編寫虛幻的 JavaScript 或 jQuery,並依賴第三方構建工具,或者根本不使用構建流程。

相比之下,wp-scripts 在幾乎所有領域都提供了現代化的整合方法:

元素  傳統開發 wp-scripts
JavaScript 通常是普通 JavaScript 或 jQuery ES6 和 React 支援
CSS 直接 CSS 或基本前處理器 支援 Sass 和 PostCSS 處理
構建過程  使用 Gulp 或 Grunt 進行手動或自定義設定 使用 webpack 進行零配置設定,整合到軟體包中。
程式碼質量 手動檢查或與程式碼編輯器整合的單獨工具  ESLint 和 Prettier 內建於 wp-scripts 中
單元測試  如果這不是一個被忽視的步驟,通常會有一個單獨的設定 包整合了 Jest 測試

總的來說,wp-scripts 提供了更大的靈活性,這要歸功於它整合了你可能尚未使用的工具。例如,設定 PostCSSwebpack 或 Jest 的工作可能會因為時間限制而被省略。

如何設定開發環境以納入wp-scripts

使用 wp-scripts 有其自身的要求,但你很可能已經在使用這些工具了。如果有必要,請安裝 Node.js 和 npm,同時安裝本地 WordPress 開發環境。

DevKinsta 主介面

DevKinsta 主介面。

如果你已經使用 create-block 軟體包來開發 WordPress Block 外掛,則會將 wp-scripts 與其他資產一起安裝。從這裡,您可以開始建立一個軟體包開發專案。

使用wp-scripts建立新的WordPress專案

您將在 WordPress 安裝的 wp-content 目錄中開展工作。具體子目錄與你建立的專案型別有關:wp-content/themes 用於主題,wp-content/plugins 用於外掛!

無論如何,你的專案資料夾都應包括一些檔案和目錄:

  • package.json 檔案。
  • 構建目錄。
  • 包含 index.js 檔案的 src 目錄。

要建立 package.json 檔案,請使用終端或命令列應用程式導航到專案目錄。執行 npm init 命令將完成互動式設定過程,“入口點”應為build/index.js

npm init 過程的部分執行

npm init 過程的部分執行,顯示入口點值提示。

接下來,將 wp-scripts 安裝為開發依賴項:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install @wordpress/scripts --save-dev
npm install @wordpress/scripts --save-dev
npm install @wordpress/scripts --save-dev

你還會看到一些自動生成的目錄和檔案:node_modulespackage-lock.json。無論如何,你現在需要在 package.json 檔案中引用預定義指令碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start",
}
"scripts": { "build": "wp-scripts build", "start": "wp-scripts start", }
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start",
}

您可能會經常返回該檔案,以便在需要時新增更多指令碼。例如:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"lint:js": "wp-scripts lint-js",
"lint:css": "wp-scripts lint-style",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"test": "wp-scripts test-unit-js"
… "lint:js": "wp-scripts lint-js", "lint:css": "wp-scripts lint-style", "lint:pkg-json": "wp-scripts lint-pkg-json", "test": "wp-scripts test-unit-js" …
…
"lint:js": "wp-scripts lint-js",
"lint:css": "wp-scripts lint-style",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"test": "wp-scripts test-unit-js"
…

您可能還需要在此處對主題或外掛資產進行排隊,然後儲存更改。

使用wp-scripts理解並使用webpack

在引擎蓋下捆綁資產時,wp-scripts 會使用 webpack。雖然瞭解 Webpack 的作用可以幫助你更有效地利用 wp-scripts,但你並不需要對其進行配置。Webpack 在你的設定中承擔了很多責任:

  • 它可以幫助解決 JavaScript 模組之間的依賴關係。
  • 它可以將現代 JavaScript 轉換為相容瀏覽器的程式碼。
  • 它可以幫助處理和優化樣式。
  • 生成源對映,讓除錯更輕鬆。
  • 它還能幫助你建立可用於生產的最小化捆綁包。

wp-scripts 中已經有了預設的 webpack 配置。這對大多數 WordPress 專案都很有效。但在某些情況下,您可能需要建立自定義配置。

針對機構設定的高階webpack配置

雖然預設的 webpack 配置是大多數開發專案的理想選擇,但有時您也需要根據自己的特定需求建立配置。例如,您可能需要處理複雜的主題結構或獨特的外掛架構。這時,專案根目錄中的 webpack.config.js 檔案就會派上用場:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const defaultConfig = require("@wordpress/scripts/config/webpack.config");
const path = require('path');
module.exports = {
...defaultConfig,
entry: {
main: path.resolve(__dirname, 'src/js/main.js'),
admin: path.resolve(__dirname, 'src/js/admin.js'),
// Add more entry points as needed
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
// Add custom loaders or plugins here
};
const defaultConfig = require("@wordpress/scripts/config/webpack.config"); const path = require('path'); module.exports = { ...defaultConfig, entry: { main: path.resolve(__dirname, 'src/js/main.js'), admin: path.resolve(__dirname, 'src/js/admin.js'), // Add more entry points as needed }, output: { filename: '[name].js', path: path.resolve(__dirname, 'dist'), }, // Add custom loaders or plugins here };
const defaultConfig = require("@wordpress/scripts/config/webpack.config");
const path = require('path');
module.exports = {
...defaultConfig,
entry: {
main: path.resolve(__dirname, 'src/js/main.js'),
admin: path.resolve(__dirname, 'src/js/admin.js'),
// Add more entry points as needed
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
// Add custom loaders or plugins here
};

這種配置允許多個入口點,對於需要為 WordPress 管理或前臺的不同部分分別編寫指令碼的主題或外掛來說尤其有用。因此,你可以擴充套件預設配置,並保持 wp-scripts 的優勢。

使用wp-scripts的基礎知識

有了合適的開發環境和正確的檔案與資料夾結構,你就可以開始使用wp-scripts 了。有幾個基本的核心命令會佔用你大部分時間。

start 命令會監控檔案變化,即時重新編譯資產,並提供熱過載功能,讓開發體驗更加流暢:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm run start
npm run start
npm run start

你可以在專案開始時使用它來啟動開發伺服器,不過它不會優化 build/index.js 檔案中的編譯程式碼。

當需要部署專案時,build 命令將為生產編譯資產:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm run build
npm run build
npm run build

執行後,它會執行一些任務。例如,它會轉譯 JavaScript、將 Sass 和 SCSS 編譯成 CSS、最小化所有資產並生成源對映。最後,它會將所有內容輸出到 build/index.js 檔案中。構建過程還會建立一個 build/index.asset.php 檔案,用於快取。

wp-scripts 軟體包還提供了幾條 linting 命令,幫助你保持程式碼的高質量:

  • npm run lint:js。用它來檢查 JavaScript 檔案。
  • npm run lint:css。用於檢查 CSS 或 Sass 檔案。
  • npm run lint:pkg-json。用於驗證package.json檔案。

對於單元測試,只需呼叫 npm run test,它就會使用 Jest 執行測試套件。

探索wp-scripts中的核心工具

基本的構建任務可能會耗費你很長時間,典型的命令需要大量的自動化操作。不過,wp-scripts提供了一套複雜的實用程式,可以滿足 WordPress 開發的複雜需求:

  • 高階編譯。通過優化配置,您可以轉譯現代 JavaScript(包括 ECMAScript Modules (ESM) 和 Javascript XML (JSX))並編譯 Sass。
  • 智慧捆綁。您可以利用 webpack 的程式碼拆分和“樹狀結構”來優化資產交付。
  • 全面的內襯。您可以在 JavaScript、CSS 和 package.json 檔案中執行編碼標準。
  • 整合測試。通過 Jest,您可以執行單元測試和覆蓋率報告。
  • 開發伺服器。您可以利用熱過載功能實現跨多個專案的快速開發。

無論您是開發主題還是外掛,您都可以擴充套件每個專案的預設功能,從而利用更個性化的 WordPress 開發流程。

處理 JSX 和現代 JavaScript

許多 WordPress 專案都使用了現代 JavaScript 元素,如 React 元件、箭頭函式、重構、async/await 等。甚至核心程式碼庫的某些方面,如塊編輯器,也使用現代 JavaScript 來構建其功能。

但是,瀏覽器並不能原生理解這些高階語法,因此需要進行更多的轉譯和編譯工作。

JSX 可讓您在 JavaScript 中編寫類似 HTML 的程式碼,從而更容易描述介面和其他元素的外觀。首先,這可以提高可讀性和可維護性。您還可以使用強大的 React 元件來建立動態使用者介面(UI)。

wp-scripts 使用 Babel JavaScript 編譯器將現代 JavaScript 和 JSX 轉換成瀏覽器可以理解的程式碼。它會處理所有複雜和必要的配置,讓你專注於編寫程式碼。

您可以通過 src/index.js 檔案利用它。請看這個小例子,瞭解如何使用 wp-scripts 實現 JSX 和現代 JavaScript:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { render } from '@wordpress/element';
// Modern JavaScript feature: Arrow function
const HelloWorld = () => {
// Modern JavaScript feature: Template literal
const greeting = `Hello, ${wp.data.select('core/editor').getCurrentPost().title}!`;
// JSX
return (
<div className="hello-world">
<h1>{greeting}</h1>
<p>This is a React component in WordPress!</p>
</div>
);
};
// Modern JavaScript feature: Optional chaining
const rootElement = document.getElementById('hello-world-root');
if (rootElement?.innerHTML) {
render(<HelloWorld />, rootElement);
}
import { render } from '@wordpress/element'; // Modern JavaScript feature: Arrow function const HelloWorld = () => { // Modern JavaScript feature: Template literal const greeting = `Hello, ${wp.data.select('core/editor').getCurrentPost().title}!`; // JSX return ( <div className="hello-world"> <h1>{greeting}</h1> <p>This is a React component in WordPress!</p> </div> ); }; // Modern JavaScript feature: Optional chaining const rootElement = document.getElementById('hello-world-root'); if (rootElement?.innerHTML) { render(<HelloWorld />, rootElement); }
import { render } from '@wordpress/element';
// Modern JavaScript feature: Arrow function
const HelloWorld = () => {
// Modern JavaScript feature: Template literal
const greeting = `Hello, ${wp.data.select('core/editor').getCurrentPost().title}!`;    
// JSX
return (
<div className="hello-world">
<h1>{greeting}</h1>
<p>This is a React component in WordPress!</p>
</div>
);
};
// Modern JavaScript feature: Optional chaining
const rootElement = document.getElementById('hello-world-root');
if (rootElement?.innerHTML) {
render(<HelloWorld />, rootElement);
}

您還必須在主題的 functions.php 檔案或主外掛檔案中啟用指令碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function enqueue_hello_world_script() {
wp_enqueue_script(
'hello-world-script',
get_template_directory_uri() . '/build/index.js',
['wp-element'],
filemtime(get_template_directory() . '/build/index.js'),
true
);
}
add_action('wp_enqueue_scripts', 'enqueue_hello_world_script');
function enqueue_hello_world_script() { wp_enqueue_script( 'hello-world-script', get_template_directory_uri() . '/build/index.js', ['wp-element'], filemtime(get_template_directory() . '/build/index.js'), true ); } add_action('wp_enqueue_scripts', 'enqueue_hello_world_script');
function enqueue_hello_world_script() {
wp_enqueue_script(
'hello-world-script',
get_template_directory_uri() . '/build/index.js',
['wp-element'],
filemtime(get_template_directory() . '/build/index.js'),
true
);
}
add_action('wp_enqueue_scripts', 'enqueue_hello_world_script');

執行 npx wp-scripts build 命令後,wp-scripts 將對現代 JavaScript 和 JSX 進行轉譯,以建立與瀏覽器相容的 build/index.js 檔案。

程式碼質量檢查和複雜的著色

wp-scripts 軟體包包含多種工具,可幫助你保持程式碼質量,並在整個專案中執行一致的風格: 除了 ESLint 和 Prettier,您還可以訪問 stylelint 進行 CSS 和 SCSS 檢查。

第一步是將inting 指令碼新增到 package.json 檔案中:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"scripts": {
"lint:js": "wp-scripts lint-js",
"lint:css": "wp-scripts lint-style",
"lint": "npm run lint:js && npm run lint:css"
}
"scripts": { "lint:js": "wp-scripts lint-js", "lint:css": "wp-scripts lint-style", "lint": "npm run lint:js && npm run lint:css" }
"scripts": {
"lint:js": "wp-scripts lint-js",
"lint:css": "wp-scripts lint-style",
"lint": "npm run lint:js && npm run lint:css"
}

接下來,在專案根目錄下建立自定義配置檔案。例如,ESLint 要求你在 .eslintrc.js 檔案中工作。該示例(部分)強制要求在 JavaScript 程式碼中使用模板字面量來表示字串:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
module.exports = {
extends: [
'plugin:@wordpress/eslint-plugin/recommended',
],
rules: {
// Custom rules here
'no-console': 'error',
'react-hooks/exhaustive-deps': 'warn',
'prefer-template': 'error',
},
};
… module.exports = { extends: [ 'plugin:@wordpress/eslint-plugin/recommended', ], rules: { // Custom rules here 'no-console': 'error', 'react-hooks/exhaustive-deps': 'warn', 'prefer-template': 'error', }, }; …
…
module.exports = {
extends: [
'plugin:@wordpress/eslint-plugin/recommended',
],
rules: {
// Custom rules here
'no-console': 'error',
'react-hooks/exhaustive-deps': 'warn',
'prefer-template': 'error',
},
};
…

要使用 stylelint,需要編輯 .stylelintrc.js 檔案:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
module.exports = {
extends: [
'@wordpress/stylelint-config/scss',
],
rules: {
// Custom rules here
'selector-class-pattern': '^[a-z]+(-[a-z]+)*$',
'max-nesting-depth': 3,
},
};
… module.exports = { extends: [ '@wordpress/stylelint-config/scss', ], rules: { // Custom rules here 'selector-class-pattern': '^[a-z]+(-[a-z]+)*$', 'max-nesting-depth': 3, }, }; …
…
module.exports = {
extends: [
'@wordpress/stylelint-config/scss',
],
rules: {
// Custom rules here
'selector-class-pattern': '^[a-z]+(-[a-z]+)*$',
'max-nesting-depth': 3,
},
};
…

如果您在多個專案中維護一個龐大的程式碼庫,擁有一致的程式碼風格至關重要。這樣,你就可以擴充套件預設的 ESLint 和 stylelint 配置,以執行你的機構的編碼標準。

在這裡,你可以執行 npm run lint 來啟動這一過程,並使用特定的執行緒型別進行擴充套件。例如,如果您的程式碼中存在一些典型的連線…

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const name = "World";
console.log("Hello " + name + "!");
const name = "World"; console.log("Hello " + name + "!");
const name = "World";
console.log("Hello " + name + "!");

……執行 npm run lint:js 會提示錯誤,並建議您使用模板文字代替:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const name = "World";
console.log(`Hello ${name}!`);
const name = "World"; console.log(`Hello ${name}!`);
const name = "World";
console.log(`Hello ${name}!`);

這是檢查 WordPress 主題或外掛程式碼的重要方法,可讓您根據具體需求和標準定製規則集。

單元測試

單元測試對於確保程式碼庫的可靠性和可維護性至關重要。wp-scripts 使用的測試框架工具是 Jest。

執行測試命令時,Jest 會查詢帶有 .test.js.spec.js 副檔名的檔案,或__tests__目錄中的檔案。然後執行這些檔案中定義的測試並報告結果。

您首先需要在 package.json 檔案中引用測試指令碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"scripts": {
"test": "wp-scripts test-unit-js"
}
… "scripts": { "test": "wp-scripts test-unit-js" } …
…
"scripts": {
"test": "wp-scripts test-unit-js"
}
…

如果需要,可建立一個檔案,如 src/utils.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export function capitalizeString(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function sum(a, b) {
return a + b;
}
… export function capitalizeString(str) { return str.charAt(0).toUpperCase() + str.slice(1); } export function sum(a, b) { return a + b; } …
…
export function capitalizeString(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function sum(a, b) {
return a + b;
}
…

從這裡建立一個測試檔案,如 src/__tests__/utils.test.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { capitalizeString, sum } from '../utils';
describe('capitalizeString', () => {
it('capitalizes the first letter of a string', () => {
expect(capitalizeString('hello')).toBe('Hello');
});
it('returns an empty string if given an empty string', () => {
expect(capitalizeString('')).toBe('');
});
});
describe('sum', () => {
it('adds two numbers correctly', () => {
expect(sum(2, 3)).toBe(5);
});
it('handles negative numbers', () => {
expect(sum(-1, 1)).toBe(0);
});
});
import { capitalizeString, sum } from '../utils'; describe('capitalizeString', () => { it('capitalizes the first letter of a string', () => { expect(capitalizeString('hello')).toBe('Hello'); }); it('returns an empty string if given an empty string', () => { expect(capitalizeString('')).toBe(''); }); }); describe('sum', () => { it('adds two numbers correctly', () => { expect(sum(2, 3)).toBe(5); }); it('handles negative numbers', () => { expect(sum(-1, 1)).toBe(0); }); });
import { capitalizeString, sum } from '../utils';
describe('capitalizeString', () => {
it('capitalizes the first letter of a string', () => {
expect(capitalizeString('hello')).toBe('Hello');
});
it('returns an empty string if given an empty string', () => {
expect(capitalizeString('')).toBe('');
});
});
describe('sum', () => {
it('adds two numbers correctly', () => {
expect(sum(2, 3)).toBe(5);
});
it('handles negative numbers', () => {
expect(sum(-1, 1)).toBe(0);
});
});

執行 npm run test 命令後,wp-scripts 會自動查詢並執行所有以 .test.js 為副檔名的檔案。您還可以擴充套件預設的 Jest 配置,以支援任何高階測試需求,例如測試覆蓋率:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// jest.config.js
const defaultConfig = require('@wordpress/scripts/config/jest-unit.config');
module.exports = {
...defaultConfig,
setupFilesAfterEnv: ['<rootDir>/tests/setupTests.js'],
collectCoverageFrom: [
'src/**/*.js',
'!src/tests/**/*.js',
'!src/vendor/**/*.js',
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
};
// jest.config.js const defaultConfig = require('@wordpress/scripts/config/jest-unit.config'); module.exports = { ...defaultConfig, setupFilesAfterEnv: ['<rootDir>/tests/setupTests.js'], collectCoverageFrom: [ 'src/**/*.js', '!src/tests/**/*.js', '!src/vendor/**/*.js', ], coverageThreshold: { global: { branches: 80, functions: 80, lines: 80, statements: 80, }, }, };
// jest.config.js
const defaultConfig = require('@wordpress/scripts/config/jest-unit.config');
module.exports = {
...defaultConfig,
setupFilesAfterEnv: ['<rootDir>/tests/setupTests.js'],
collectCoverageFrom: [
'src/**/*.js',
'!src/tests/**/*.js',
'!src/vendor/**/*.js',
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
};

此配置新增了一個自定義設定檔案,指定了要包含在覆蓋率報告中的檔案,並設定了覆蓋率閾值,以確保在整個專案中實現全面的測試覆蓋率。執行這些測試時,Jest 會提供輸出,顯示所有通過和未通過的測試。

通過這種方式擴充套件單元測試功能,可以大大提高 WordPress 主題和外掛的質量和可靠性,並簡化整個開發流程。

如何將wp-scripts整合到工作流程中

wp指令碼的使用範圍非常廣泛。為了說明這一點,讓我們回顧一下使用 wp-scripts 自動執行典型任務的一些快速方法。

建立可重複使用的專案模板

您可能需要經常啟動新專案,甚至可能每天都需要。通過預配置wp-scripts 建立自定義專案模板,可以節省大量設定時間。

你可以從一個基礎專案開始:一個包含 wp-scripts 設定的新 WordPress 主題或外掛:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mkdir my-agency-base-theme
cd my-agency-base-theme
npm init -y
npm install --save-dev @wordpress/scripts
mkdir my-agency-base-theme cd my-agency-base-theme npm init -y npm install --save-dev @wordpress/scripts
mkdir my-agency-base-theme
cd my-agency-base-theme
npm init -y
npm install --save-dev @wordpress/scripts

接下來,設定專案結構,建立必要的目錄和檔案:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mkdir src build
touch src/index.js src/style.scss
touch functions.php style.css
mkdir src build touch src/index.js src/style.scss touch functions.php style.css
mkdir src build
touch src/index.js src/style.scss
touch functions.php style.css

此時,您需要配置 wp-scripts,並用相關命令更新 package.json 檔案:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start",
"lint:js": "wp-scripts lint-js",
"lint:css": "wp-scripts lint-style",
"test": "wp-scripts test-unit-js"
}
}
{ "scripts": { "build": "wp-scripts build", "start": "wp-scripts start", "lint:js": "wp-scripts lint-js", "lint:css": "wp-scripts lint-style", "test": "wp-scripts test-unit-js" } }
{
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start",
"lint:js": "wp-scripts lint-js",
"lint:css": "wp-scripts lint-style",
"test": "wp-scripts test-unit-js"
}
}

在此基礎上,您還可以為 webpack、ESLint 和 stylelint 建立配置。

為使該模板可重複使用且易於訪問,GitHub repo 是理想的選擇。例如,考慮 https://github.com/your-agency/theme-template.git 的遠端源。

當你開始一個新專案時,可以直接執行一個命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-wordpress-theme@latest my-new-theme --template your-agency/theme-template
npx create-wordpress-theme@latest my-new-theme --template your-agency/theme-template
npx create-wordpress-theme@latest my-new-theme --template your-agency/theme-template

這將克隆你的模板 repo,並使用預定義的 wp-scripts 配置設定一個新主題。

您可以通過新增特定機構的模板程式碼(如常用函式或元件)來進一步自定義模板。重要的是要保持該模板庫的最新狀態,使用最新的wp-scripts版本,並實施您決定的任何工作流程改進。

版本控制和協作

說到 wp-scripts 和版本控制,你可以做得更多。但通常情況下,你應該實施一些典型的做法,以確保程式碼的高質量:

  • 在版本控制中包含 package.jsonpackage-lock.json。這樣可以確保所有團隊成員使用相同的依賴關係。
  • 確保在 .gitignore 檔案中包含 /build /node_modules 等構建工件。
  • 在提交 package.json 檔案之前,確保在其中引用了所有需要的指令碼。
  • 考慮使用 .nvmrc 檔案為專案指定正確的 Node.js 版本。

您可以選擇通過 Husky 等工具實施預提交鉤子。例如,這就是在每次提交前執行執行緒的好方法:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"husky": {
"hooks": {
"pre-commit": "npm run lint:js && npm run lint:css"
}
}
… "husky": { "hooks": { "pre-commit": "npm run lint:js && npm run lint:css" } } …
…
"husky": {
"hooks": {
"pre-commit": "npm run lint:js && npm run lint:css"
}
}
…

這樣,你就能確保在提交和推送前自動進行校驗和執行測試。這也是在整個團隊中保持程式碼質量的另一種方法。

持續整合和持續部署(CI/CD)

wp-scripts 整合到 CI/CD 管道中可以簡化主題和外掛的部署流程。GitHub Actions 只是將其整合到 wp-scripts 配置中的一種方法。

第一步是在倉庫的 workflows 目錄中建立一個專門的工作流檔案:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
name: CI/CD
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }}
- name: Install dependencies
run: npm ci
- name: Run linters
run: |
npm run lint:js
npm run lint:css
- name: Run tests
run: npm run test
- name: Build
run: npm run build
- name: Deploy
if: github.ref == 'refs/heads/main'
run: |
# Add your deployment script here
# For example, using rsync to a remote server:
# rsync -avzc --delete ./build/ user@example.com:/path/to/wp-content/themes/your-theme/
name: CI/CD on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build-and-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version: '14' - name: Cache dependencies uses: actions/cache@v2 with: path: ~/.npm key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }} - name: Install dependencies run: npm ci - name: Run linters run: | npm run lint:js npm run lint:css - name: Run tests run: npm run test - name: Build run: npm run build - name: Deploy if: github.ref == 'refs/heads/main' run: | # Add your deployment script here # For example, using rsync to a remote server: # rsync -avzc --delete ./build/ user@example.com:/path/to/wp-content/themes/your-theme/
name: CI/CD
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }}
- name: Install dependencies
run: npm ci
- name: Run linters
run: |
npm run lint:js
npm run lint:css
- name: Run tests
run: npm run test
- name: Build
run: npm run build
- name: Deploy
if: github.ref == 'refs/heads/main'
run: |
# Add your deployment script here
# For example, using rsync to a remote server:
# rsync -avzc --delete ./build/ user@example.com:/path/to/wp-content/themes/your-theme/

部署步驟因主機而異。你可以使用 rsync、與 DeployHQ 或 Buddy 等服務整合,也可以使用簡單的 cURL 整合。如果部署需要密碼或金鑰,則應將它們作為機密新增到 GitHub 倉庫設定中。

該工作流在每次推送和拉取請求時都會執行 linters、測試和構建專案。最重要的是,它只在你向主分支推送變更時才進行部署。

建立自定義命令列介面(CLI)工具

如果你需要自定義工具,wp-scripts 可以提供幫助。例如,你可能想部署一個符合你的機構需求的自定義 CLI 工具。

在某些情況下,您的工具需要一些依賴項:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install @wordpress/scripts commander chalk
npm install @wordpress/scripts commander chalk
npm install @wordpress/scripts commander chalk

在這裡,Commander 會解析命令列引數,並用 chalk 改進輸出文字的視覺化顯示。

從這裡開始,你就可以利用 wp-scripts 來編寫工具程式碼了。以下是該檔案的示例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/usr/bin/env node
const { program } = require('commander');
const { spawn } = require('child_process');
const path = require('path');
const chalk = require('chalk');
const wpScripts = path.resolve(__dirname, './node_modules/.bin/wp-scripts');
const runWpScripts = (script, args) => {
console.log(chalk.blue(`Running wp-scripts ${script}...`));
const result = spawn(wpScripts, [script, ...args], { stdio: 'inherit' });
result.on('exit', (code) => {
if (code !== 0) {
console.log(chalk.red(`wp-scripts ${script} failed with code ${code}`));
}
});
};
program
.version('1.0.0')
.description('Custom WordPress development CLI for Agency XYZ');
program
.command('build')
.description('Build the project')
.action(() => runWpScripts('build'));
program
.command('start')
.description('Start the development server')
.action(() => runWpScripts('start'));
program
.command('lint')
.description('Lint JavaScript and CSS files')
.action(() => {
runWpScripts('lint-js');
runWpScripts('lint-style');
});
program
.command('test')
.description('Run unit tests')
.action(() => runWpScripts('test-unit-js'));
program
.command('deploy')
.description('Deploy the project')
.action(() => {
console.log(chalk.green('Deploying project...'));
// Add your deployment logic here
// For example:
// spawn('rsync', ['-avz', 'build/', 'user@server:/path/to/wordpress/wp-content/themes/your-theme/']);
});
program.parse(process.argv);
#!/usr/bin/env node const { program } = require('commander'); const { spawn } = require('child_process'); const path = require('path'); const chalk = require('chalk'); const wpScripts = path.resolve(__dirname, './node_modules/.bin/wp-scripts'); const runWpScripts = (script, args) => { console.log(chalk.blue(`Running wp-scripts ${script}...`)); const result = spawn(wpScripts, [script, ...args], { stdio: 'inherit' }); result.on('exit', (code) => { if (code !== 0) { console.log(chalk.red(`wp-scripts ${script} failed with code ${code}`)); } }); }; program .version('1.0.0') .description('Custom WordPress development CLI for Agency XYZ'); program .command('build') .description('Build the project') .action(() => runWpScripts('build')); program .command('start') .description('Start the development server') .action(() => runWpScripts('start')); program .command('lint') .description('Lint JavaScript and CSS files') .action(() => { runWpScripts('lint-js'); runWpScripts('lint-style'); }); program .command('test') .description('Run unit tests') .action(() => runWpScripts('test-unit-js')); program .command('deploy') .description('Deploy the project') .action(() => { console.log(chalk.green('Deploying project...')); // Add your deployment logic here // For example: // spawn('rsync', ['-avz', 'build/', 'user@server:/path/to/wordpress/wp-content/themes/your-theme/']); }); program.parse(process.argv);
#!/usr/bin/env node
const { program } = require('commander');
const { spawn } = require('child_process');
const path = require('path');
const chalk = require('chalk');
const wpScripts = path.resolve(__dirname, './node_modules/.bin/wp-scripts');
const runWpScripts = (script, args) => {
console.log(chalk.blue(`Running wp-scripts ${script}...`));
const result = spawn(wpScripts, [script, ...args], { stdio: 'inherit' });
result.on('exit', (code) => {
if (code !== 0) {
console.log(chalk.red(`wp-scripts ${script} failed with code ${code}`));
}
});
};
program
.version('1.0.0')
.description('Custom WordPress development CLI for Agency XYZ');
program
.command('build')
.description('Build the project')
.action(() => runWpScripts('build'));
program
.command('start')
.description('Start the development server')
.action(() => runWpScripts('start'));
program
.command('lint')
.description('Lint JavaScript and CSS files')
.action(() => {
runWpScripts('lint-js');
runWpScripts('lint-style');
});
program
.command('test')
.description('Run unit tests')
.action(() => runWpScripts('test-unit-js'));
program
.command('deploy')
.description('Deploy the project')
.action(() => {
console.log(chalk.green('Deploying project...'));
// Add your deployment logic here
// For example:
// spawn('rsync', ['-avz', 'build/', 'user@server:/path/to/wordpress/wp-content/themes/your-theme/']);
});
program.parse(process.argv);

在 package.json 檔案中新增 bin 欄位可讓 CLI 工具成為可執行檔案:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"name": "agency-wp-cli",
"version": "1.0.0",
"bin": {
"agency-wp": "./cli.js"
},
// ... other fields
}
… { "name": "agency-wp-cli", "version": "1.0.0", "bin": { "agency-wp": "./cli.js" }, // ... other fields } …
…
{
"name": "agency-wp-cli",
"version": "1.0.0",
"bin": {
"agency-wp": "./cli.js"
},
// ... other fields
}
…

要為本地安裝連結 CLI,只需執行 npm link。現在,你可以在終端應用程式中測試 CLI 了:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
agency-wp build
agency-wp lint
agency-wp deploy
agency-wp build agency-wp lint agency-wp deploy
agency-wp build
agency-wp lint
agency-wp deploy

您應該將該工具釋出到私有的 npm 登錄檔中,這樣其他團隊成員就可以隨意安裝:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm publish --registry=https://your-private-registry.com
npm publish --registry=https://your-private-registry.com
npm publish --registry=https://your-private-registry.com

需要時,只需執行 npm install --save-dev agency-wp-cli 即可安裝工具。在這裡,你可以在 package.json 中引用 CLI:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"scripts": {
"build": "agency-wp build",
"start": "agency-wp start",
"lint": "agency-wp lint",
"test": "agency-wp test",
"deploy": "agency-wp deploy"
}
}
{ "scripts": { "build": "agency-wp build", "start": "agency-wp start", "lint": "agency-wp lint", "test": "agency-wp test", "deploy": "agency-wp deploy" } }
{
"scripts": {
"build": "agency-wp build",
"start": "agency-wp start",
"lint": "agency-wp lint",
"test": "agency-wp test",
"deploy": "agency-wp deploy"
}
}

建立和使用這樣的工具可以確保您公司的每個人都使用相同的命令和流程。這可以減少不一致,並進一步簡化 WordPress 開發工作流程。

效能優化

在管理多個高流量 WordPress 網站時,效能優化對您的交付至關重要。wp-scripts 可以幫助您實現多種高階技術。

高階程式碼拆分

例如,通過程式碼拆分,您可以將 JavaScript 捆綁程式拆分成更小的塊,然後按需載入。這可以提高初始載入時間,尤其是大型應用程式。

首先,修改 webpack.config.js 檔案以啟用程式碼拆分:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
module.exports = {
...defaultConfig,
entry: {
main: './src/index.js',
admin: './src/admin.js',
},
output: {
filename: '[name].js',
chunkFilename: '[name].[contenthash].js',
},
optimization: {
...defaultConfig.optimization,
splitChunks: {
chunks: 'all',
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `vendor.${packageName.replace('@', '')}`;
},
},
},
},
},
};
const defaultConfig = require('@wordpress/scripts/config/webpack.config'); module.exports = { ...defaultConfig, entry: { main: './src/index.js', admin: './src/admin.js', }, output: { filename: '[name].js', chunkFilename: '[name].[contenthash].js', }, optimization: { ...defaultConfig.optimization, splitChunks: { chunks: 'all', minSize: 0, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name(module) { const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]; return `vendor.${packageName.replace('@', '')}`; }, }, }, }, }, };
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
module.exports = {
...defaultConfig,
entry: {
main: './src/index.js',
admin: './src/admin.js',
},
output: {
filename: '[name].js',
chunkFilename: '[name].[contenthash].js',
},
optimization: {
...defaultConfig.optimization,
splitChunks: {
chunks: 'all',
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `vendor.${packageName.replace('@', '')}`;
},
},
},
},
},
};

在整個 JavaScript 程式碼中,您使用動態匯入將其分割成小塊:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Instead of: import { heavyFunction } from './heavyModule';
button.addEventListener('click', () => {
import('./heavyModule').then(module => {
module.heavyFunction();
});
});
// Instead of: import { heavyFunction } from './heavyModule'; button.addEventListener('click', () => { import('./heavyModule').then(module => { module.heavyFunction(); }); });
// Instead of: import { heavyFunction } from './heavyModule';
button.addEventListener('click', () => {
import('./heavyModule').then(module => {
module.heavyFunction();
});
});

您還需要在 WordPress 檔案中對每個分割進行排隊:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function enqueue_split_scripts() {
$asset_file = include(get_template_directory() . '/build/index.asset.php');
wp_enqueue_script('main', get_template_directory_uri() . '/build/main.js', $asset_file['dependencies'], $asset_file['version'], true);
wp_enqueue_script('admin', get_template_directory_uri() . '/build/admin.js', $asset_file['dependencies'], $asset_file['version'], true);
}
add_action('wp_enqueue_scripts', 'enqueue_split_scripts');
function enqueue_split_scripts() { $asset_file = include(get_template_directory() . '/build/index.asset.php'); wp_enqueue_script('main', get_template_directory_uri() . '/build/main.js', $asset_file['dependencies'], $asset_file['version'], true); wp_enqueue_script('admin', get_template_directory_uri() . '/build/admin.js', $asset_file['dependencies'], $asset_file['version'], true); } add_action('wp_enqueue_scripts', 'enqueue_split_scripts');
function enqueue_split_scripts() {
$asset_file = include(get_template_directory() . '/build/index.asset.php');  
wp_enqueue_script('main', get_template_directory_uri() . '/build/main.js', $asset_file['dependencies'], $asset_file['version'], true);
wp_enqueue_script('admin', get_template_directory_uri() . '/build/admin.js', $asset_file['dependencies'], $asset_file['version'], true);
}
add_action('wp_enqueue_scripts', 'enqueue_split_scripts');

這樣可以降低載入時間,而且實施起來也不會花費太多時間。

樹形調整

在 JavaScript 中,‘tree shaking’是指如何刪除未使用的程式碼。wp-scriptswebpack 都會在生產構建時進行樹形調整,但你還可以進一步優化。應用比我們這裡給出的更復雜,但無論如何,你都要確保使用 ES6 匯入和匯出語法:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Good for tree shaking
export function usedFunction() { /* ... */ }
// Bad for tree shaking
module.exports = {
usedFunction: function() { /* ... */ },
};
// Good for tree shaking export function usedFunction() { /* ... */ } // Bad for tree shaking module.exports = { usedFunction: function() { /* ... */ }, };
// Good for tree shaking
export function usedFunction() { /* ... */ }
// Bad for tree shaking
module.exports = {
usedFunction: function() { /* ... */ },
};

接下來,指定那些有 ‘side effects’的檔案…

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"name": "your-package",
"sideEffects": ["*.css", "*.scss"]
}
{ "name": "your-package", "sideEffects": ["*.css", "*.scss"] }
{
"name": "your-package",
"sideEffects": ["*.css", "*.scss"]
}

…或標記為無副作用:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"name": "your-package",
"sideEffects": false
}
{ "name": "your-package", "sideEffects": false }
{
"name": "your-package",
"sideEffects": false
}

有些大型庫和其他庫一樣,不支援樹形晃動。在這種情況下,您應該使用特定的外掛來完成這項工作:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install --save-dev babel-plugin-transform-imports
npm install --save-dev babel-plugin-transform-imports
npm install --save-dev babel-plugin-transform-imports

這也意味著您也應該更新您的 babel 配置檔案,以實現最佳和無差錯安裝。

資產優化

wp-scripts 構建過程會幫你最小化 CSS 和 JavaScript 檔案,你還可以進一步優化。例如,您可以安裝特定的圖片優化外掛:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install --save-dev imagemin-webpack-plugin
npm install --save-dev imagemin-webpack-plugin
npm install --save-dev imagemin-webpack-plugin

將其新增到 webpack 配置檔案後,只需在 functions.php 檔案或主外掛檔案中新增正確的程式碼,即可使用資源提示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function add_resource_hints( $urls, $relation_type ) {
if ( 'preconnect' === $relation_type ) {
$urls[] = 'https://fonts.googleapis.com';
$urls[] = 'https://fonts.gstatic.com';
}
return $urls;
}
add_filter( 'wp_resource_hints', 'add_resource_hints', 10, 2 );
function add_resource_hints( $urls, $relation_type ) { if ( 'preconnect' === $relation_type ) { $urls[] = 'https://fonts.googleapis.com'; $urls[] = 'https://fonts.gstatic.com'; } return $urls; } add_filter( 'wp_resource_hints', 'add_resource_hints', 10, 2 );
function add_resource_hints( $urls, $relation_type ) {
if ( 'preconnect' === $relation_type ) {
$urls[] = 'https://fonts.googleapis.com';
$urls[] = 'https://fonts.gstatic.com';
}
return $urls;
}
add_filter( 'wp_resource_hints', 'add_resource_hints', 10, 2 );

這樣的任務顯示了 wp-scripts 的靈活性,您可以根據機構或專案的需要對其進行定製。

分析捆綁大小

瞭解捆綁包的組成對於優化至關重要。有了 wp-scripts,你可以使用 --analyze 標誌來輕鬆實現這一目標。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm run build -- --analyze
npm run build -- --analyze
npm run build -- --analyze

第一步是在 package.json 檔案中新增相關指令碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"scripts": {
"analyze": "wp-scripts build --analyze"
}
}
{ "scripts": { "analyze": "wp-scripts build --analyze" } }
{
"scripts": {
"analyze": "wp-scripts build --analyze"
}
}

執行 analyze 命令後,它會生成一份報告,顯示捆綁包中每個模組的大小。這種簡單的實現方式可以幫助你確定需要優化的地方。

實施關鍵CSS

網站的關鍵CSS是載入頁面上部內容所需的最低限度。將 CSS 內嵌到頁面中可以縮短頁面的載入時間。

實現這一點需要使用 Critical CSS Webpack 外掛:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install --save-dev critical-css-webpack-plugin
npm install --save-dev critical-css-webpack-plugin
npm install --save-dev critical-css-webpack-plugin

下一步工作是更新 webpack 配置檔案,以引用該外掛:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const CriticalCssPlugin = require('critical-css-webpack-plugin');
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
module.exports = {
...defaultConfig,
plugins: [
...defaultConfig.plugins,
new CriticalCssPlugin({
base: 'dist/',
src: 'index.html',
target: 'styles/critical.css',
extract: true,
inline: true,
minify: true,
dimensions: [
{
height: 500,
width: 300,
},
{
height: 900,
width: 1300,
},
],
}),
],
};
const CriticalCssPlugin = require('critical-css-webpack-plugin'); const defaultConfig = require('@wordpress/scripts/config/webpack.config'); module.exports = { ...defaultConfig, plugins: [ ...defaultConfig.plugins, new CriticalCssPlugin({ base: 'dist/', src: 'index.html', target: 'styles/critical.css', extract: true, inline: true, minify: true, dimensions: [ { height: 500, width: 300, }, { height: 900, width: 1300, }, ], }), ], };
const CriticalCssPlugin = require('critical-css-webpack-plugin');
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
module.exports = {
...defaultConfig,
plugins: [
...defaultConfig.plugins,
new CriticalCssPlugin({
base: 'dist/',
src: 'index.html',
target: 'styles/critical.css',
extract: true,
inline: true,
minify: true,
dimensions: [
{
height: 500,
width: 300,
},
{
height: 900,
width: 1300,
},
],
}),
],
};

要使用它,您需要在 header.php 檔案中新增一個片段:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<style>
<?php echo file_get_contents(get_template_directory() . '/build/styles/critical.css'); ?>
</style>
<style> <?php echo file_get_contents(get_template_directory() . '/build/styles/critical.css'); ?> </style>
<style>
<?php echo file_get_contents(get_template_directory() . '/build/styles/critical.css'); ?>
</style>

這主要是提取並內嵌關鍵 CSS,以加快初始呈現速度。它可為特定視口尺寸生成關鍵 CSS,從而縮短主題的載入時間。

總結

對於機構開發而言,wp-scripts 是一個強大的工具,可以顯著提升主題和外掛專案的工作流程。wp-scripts 提供標準化的構建流程、現代 JavaScript 支援以及整合的測試和襯墊工具,讓您可以專注於建立高質量的 WordPress 專案,同時將一些最重要的任務自動化。

利用 wp-scripts 不僅能幫助您跟上現代開發實踐。它還能讓你站在 WordPress 開發的最前沿,隨時應對你的公司所面臨的挑戰和機遇。

wp-scripts 能為您的公司開發專案提供所需的功能和範圍嗎?請在下面的評論區與我們分享您的想法!

評論留言