Skip to content

JSX & Setup @wordpress/scripts

Gambaran Umum

Video ini membahas cara setup JSX dalam pengembangan block WordPress menggunakan @wordpress/scripts — build tool resmi dari tim WordPress yang mengompilasi JSX menjadi JavaScript standar yang dipahami browser.


Apa Itu JSX?

JSX adalah sintaks extension untuk JavaScript yang terlihat seperti HTML. JSX BUKAN JavaScript standar — browser tidak bisa membacanya langsung.

jsx
// JSX (mudah dibaca, tapi browser tidak paham):
<div className="wrapper">
  <h3>Hello</h3>
  <input type="text" onChange={handleChange} />
</div>

// Di-compile menjadi JavaScript (browser paham):
wp.element.createElement('div', { className: 'wrapper' },
  wp.element.createElement('h3', null, 'Hello'),
  wp.element.createElement('input', { type: 'text', onChange: handleChange })
);

Setup Proyek

Langkah 1: Inisialisasi npm

Di folder plugin, jalankan:

bash
npm init -y

-y = skip semua pertanyaan, gunakan default values.

Langkah 2: Install @wordpress/scripts

bash
npm install @wordpress/scripts --save-dev

--save-dev = dependency untuk development saja, bukan production.

Langkah 3: Setup package.json Scripts

Buka package.json dan tambahkan/edit bagian scripts:

json
{
  "scripts": {
    "build": "wp-scripts build",
    "start": "wp-scripts start"
  },
  "devDependencies": {
    "@wordpress/scripts": "^..."
  }
}
ScriptFungsi
npm run buildCompile JSX sekali (untuk production)
npm run startWatch mode — compile otomatis setiap kali file berubah

Langkah 4: Buat Struktur Folder

plugin-folder/
  ├── src/              ← Source files (JSX)
  │   └── index.js      ← File utama
  ├── build/            ← Output (auto-generated)
  │   └── index.js      ← JavaScript yang di-compile
  ├── package.json
  └── index.php         ← PHP plugin file

Konvensi: Tulis kode di src/index.js, build tool akan menghasilkan build/index.js.

Langkah 5: Jalankan Build

bash
npm run start

Sekarang setiap kali kamu save file di src/, build tool otomatis compile ke build/.


Update PHP: Load Build File

Ubah path JavaScript di PHP agar mengarah ke file yang sudah di-compile:

php
function adminAssets() {
  wp_register_script(
    'ournewblocktype',
    plugin_dir_url(__FILE__) . 'build/index.js',  // ← Dari build folder
    array('wp-blocks', 'wp-element')
  );
  
  register_block_type('ourplugin/are-you-paying-attention', array(
    'editor_script' => 'ournewblocktype'
  ));
}

Aturan JSX:

  1. Satu root element — JSX harus mengembalikan satu elemen pembungkus
jsx
// ❌ Error (dua root elements):
return (
  <h3>Title</h3>
  <p>Content</p>
);

// ✅ Benar (satu root):
return (
  <div>
    <h3>Title</h3>
    <p>Content</p>
  </div>
);

// ✅ Alternatif: React Fragment
return (
  <>
    <h3>Title</h3>
    <p>Content</p>
  </>
);
  1. className bukan class — karena class adalah reserved word di JavaScript
jsx
<div className="my-wrapper">   // ✅
<div class="my-wrapper">       // ❌
  1. Self-closing tags untuk elemen tanpa children
jsx
<input type="text" />     // ✅
<br />                     // ✅
<img src="photo.jpg" />   // ✅
  1. Dynamic values menggunakan curly braces {}
jsx
<p>{props.attributes.question}</p>
<input value={myVariable} onChange={handleChange} />

VS Code Tip: JSX Support

Tambahkan setting di VS Code agar file .js mendapatkan JSX tab triggers dan syntax highlighting:

json
// settings.json
{
  "files.associations": {
    "*.js": "javascriptreact"
  }
}

Contoh Block Type dengan JSX

jsx
// src/index.js

wp.blocks.registerBlockType('ourplugin/are-you-paying-attention', {
  title: 'Are You Paying Attention?',
  icon: 'smiley',
  category: 'common',
  attributes: {
    skyColor: { type: 'string' },
    grassColor: { type: 'string' }
  },
  edit: function(props) {
    function updateSkyColor(event) {
      props.setAttributes({ skyColor: event.target.value });
    }
    function updateGrassColor(event) {
      props.setAttributes({ grassColor: event.target.value });
    }
    return (
      <div>
        <input type="text" placeholder="sky color" value={props.attributes.skyColor} onChange={updateSkyColor} />
        <input type="text" placeholder="grass color" value={props.attributes.grassColor} onChange={updateGrassColor} />
      </div>
    );
  },
  save: function(props) {
    return (
      <p>Today the sky is {props.attributes.skyColor} and the grass is {props.attributes.grassColor}.</p>
    );
  }
});

Proses Compile

src/index.js (JSX)

    ▼  npm run build / npm run start

build/index.js (JavaScript standar)

    ▼  wp_register_script() di PHP

Browser (editor WordPress)