A custom blocks compiler and TypeScript helper package.

Source code (compiler): packages/packages/compiler at main · AtomicSmash/packages

NPM package (compiler): @atomicsmash/compiler – npm

Source code (TS helpers): packages/packages/blocks-helpers at main · AtomicSmash/packages

NPM package (TS helpers): @atomicsmash/blocks-helpers – npm

While in the early stages of building blocks for Launchpad, I realised that one of the hardest parts of building blocks was a lack of TypeScript support. I had already been using TypeScript over JavaScript for project code, however WordPress was lagging behind in its implementation (still is, really). One major pain point was needing to define almost everything for a block in a JSON file, which made it impossible to interpret it within related JS files.

To solve this issue, I established a block.json.ts standard, and created a custom compiler to convert this to a JSON file on build. At the same time I created TypeScript types for the block.json file and interpolation types so I could pass things like attributes and context types into the Edit function, adding type safety and other TypeScript benefits to the WordPress block building ecosystem. I was also able to set SCSS stylesheets and TypeScript src files referenced in the block.json to compile alongside the block, keeping styles and scripts optimised with the block.

This TypeScript setup makes building native blocks 10 times easier, but there’s still one (managable) downside. WordPress requires a lot of packages (such as @wordpress/block-editor) to build blocks, but a lot of those packages don’t have first party TypeScript support yet, and the 3rd party types are often outdated or incorrect. This means you often need to overwrite or ignore types for certain components, which makes building blocks over time more complicated than simply consuming types from the package, however the benefits of this system definitely outweigh the cons, and WordPress is actively working on improving its TypeScript support for these packages which should hopefully make this easier in future.


Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.