ahmadawais / create-guten-block

📦 A zero-configuration #0CJS developer toolkit for building WordPress Gutenberg block plugins.
https://Awais.dev/cgb-post
MIT License
3.15k stars 328 forks source link

Handle ES Modules properly on client / frontend (save & edit) #279

Closed Gustl22 closed 4 years ago

Gustl22 commented 4 years ago

Feature Request

First of all: I'm new to Gutenberg blocks. However, I haven't found any docs to encounter my approach, and it was hard to find a solution. Either I was not able to get a good explanation for this scenario or noone ever asked.

To make it clear I call:

I want to encounter these problems:

I know that seem to be multiple issues, but I think they are closely related.

1 Documentation for client-side scripts

I want to use ESnext modules installed with node / npm in my cgb-plugin on client-side. Sure I can use wp_enqueue_script for that, but I want this to load whole modules encapsulated in the plugin itself. For that there already exists: #227 #135 and especially #73 with focus on this comment.

So the solution is to rename editor_script to script in the function register_block_type in init.php to load scripts. There should be a comment in code or an alternative approach to use easier include scripts for client/save-case, too.

Refernce to WP Docs.

2 Import ES Modules with css files

Next I wanted to import an es6 module (here fullcalendar), but then a webpack error message occured.

Failed to compile. 
./node_modules/@fullcalendar/core/main.css
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.

So the module related css files couldn't be loaded.

Solved this by adding css-loader to webpack.config.dev.js and webpack.config.prod.js in the section module.rules

{ test: /\.css$/, loader: "style-loader!css-loader" },

3 Load block assets only, if block is present

With above approach the stuff is loaded on every page. Maybe that's the purpose for the editor, but I think not for the save-part. So that's more a question, what is the best practice to avoid loading scripts on the front-end, see?

I'm also happy to make a PR, but as I'm a newby in Gutenberg I do not consider this as a good idea. Maybe I just overlooked something. Thanks for your attendance.

Gustl22 commented 4 years ago

Seems that this project got obsolete with help of @wordpress/scripts using npm init @wordpress/block my-block However there exist the exact same issues, so I wrote down my experiences: https://wordpress.stackexchange.com/a/367847/181822