As developers, weโre constantly looking for ways to modernize our development workflow, make our code more maintainable, and align with the best practices of modern JavaScript and CSS. Thatโs where @wordpress/scripts
comes in.
In this blog post, weโll walk through what @wordpress/scripts
is, why it matters, and how we can use it to enhance our theme development workflow. Whether weโre building custom blocks or modernizing our themeโs front-end assets, @wordpress/scripts
offers us a standardized, powerful toolkit that simplifies the setup.
What is @wordpress/scripts
?
@wordpress/scripts
is a package provided by the WordPress core team that bundles together the necessary tools (like Babel, Webpack, ESLint, Prettier, etc.) to support modern JavaScript and CSS development โ without the hassle of manual configuration.
Instead of writing a bunch of Webpack configs or managing multiple dev dependencies, we can just install @wordpress/scripts
and get started immediately. Itโs optimized for building blocks and modern WordPress themes.
Setting Up Our Theme with @wordpress/scripts
1. Create or Navigate to Our Theme
cd wp-content/themes/my-theme
2. Initialize NPM and Install @wordpress/scripts
npm init -y npm install @wordpress/scripts --save-dev
File Structure Example
our-custom-theme/ โโโ assets/ โ โโโ js/ โ โ โโโ index.js โ โโโ css/ โ โโโ style.scss โโโ functions.php โโโ index.php โโโ package.json โโโ style.css
Writing Modern JavaScript
Inside assets/js/index.js
, we can write modern JavaScript using ES6+ features.
We can also import dependencies or React components if needed for block development.
const message = 'Hello from @wordpress/scripts!'; console.log(message);
Writing SCSS with Modern Features
In assets/css/style.scss
, we can use SCSS syntax.
$primary-color: #0073aa; body { background-color: $primary-color; font-family: 'Helvetica Neue', sans-serif; }
Add Build Scripts to package.json
"scripts": { "build": "wp-scripts build", "start": "wp-scripts start", "lint:js": "wp-scripts lint-js", "format:js": "wp-scripts format-js" }
Enqueue Compiled Assets in functions.php
function my_theme_enqueue_assets() { $theme_version = wp_get_theme()->get( 'Version' ); wp_enqueue_style( 'my-theme-style', get_template_directory_uri() . '/build/style.css', [], $theme_version ); wp_enqueue_script( 'my-theme-script', get_template_directory_uri() . '/build/index.js', [], $theme_version, true ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' );
Conclusion
Using @wordpress/scripts
can be a game-changer for us as WordPress developers. It simplifies the setup, encourages modern practices, and integrates seamlessly with how WordPress expects themes and blocks to be built today.
Leave a Reply