• Hi,
    I am developing a Gutenberg block (plug-in) that shall use some JavaScript in the front end, implemented in ESNext+JSX and compiled using npm. Currently, the front-end JavaScript is enqueued from a js file (ES5) that is not compiled. It works, but I was wondering if there is a better way to do (that would typically allow for a safe use of ESNext).

    Some details about my current implementation:
    The project was initiated using create-guten-block and follows the obtained structured:

    project
    │   package.json
    │   package-lock.json
    │   plugin.php
    │   readme.md
    │
    └── dist
    │   │   blocks.build.js
    │   │   blocks.editor.build.css
    │   │   blocks.style.build.css
    │
    └── node_modules
    │   │   ...
    │
    └── src
        │   blocks.js
        │   common.scss
        │   init.php
        │
        └── block
            │   block.js
            │   editor.scss
            │   style.scss

    npm compiles js and scss files from src/ to dist/. plugin.php includes init.php, that refers to the js and css files in dist/.
    I added my ES5 javascript as frontend.js in src/ (src/frontend.js), and it is enqueued to my WordPress pages using:

    function myblock_frontend_script() {
        wp_enqueue_script(
            'myblock-frontend',
            plugins_url( 'src/frontend.js', dirname( __FILE__ ) ),
            array( 'jquery' ),
            null
        );
    }
    add_action( 'wp_enqueue_scripts', 'myblock_frontend_script' );

    As I said before, it works. But is there any way to have my src/frontend.js compiled by npm toward dist/ (as src/blocks.js and hence the included src/block/block.js is), so that I can use ESNext+JSX?

    • This topic was modified 6 years, 1 month ago by Bunker D.
Viewing 1 replies (of 1 total)
  • Dani Llewellyn

    (@diddledani)

    As far as I can tell, to achieve this you can either:

    • add a new command to call webpack directly for your front-end scripts and use create-guten-block script for the editor code, or
    • eject from create-guten-block to copy all the webpack configuration from cgb into your project and customise from there

    For the first option, edit the package.json file to add your custom build script into the scripts object – you likely want to investigate how to configure webpack for your front-end code and call the build of that:

    {
        ...
        "scripts": {
            "build": "cgb-scripts build && my-custom-builder"
        }
    }
Viewing 1 replies (of 1 total)

The topic ‘Front-end JavaScipt and npm (ESNext+JSX)’ is closed to new replies.