If you are using any default theme of WordPress like twenty nineteen then there will be one file named package.json but if you are using any custom theme then you need to generate package.json first.
package.json is a file which is mainly used to store the metadata associated with your project. It is also used to store the list of dependency packages. If you want to add any package in your project then you need to create package.json file.
To create package.json file, first of all, move to your theme’s root directory and run the following command.
After running the above command it will prompt some questions. Answer all the questions and that’s it. You have successfully generated your packge.json file. You can see it inside your theme’s root directory.
Move to your theme’s root directory and run following command.
After running this command you can see one folder named node_modules added inside your theme’s root directory which contains all the required packages and modules.
After installation completed, create one folder named src inside your theme’s root directory and add your js file inside it. Note: It is required to name your js file as index.js as react starts rendering all the components from index.js file.
Add one another folder named build inside your theme’s root directory.
Note: Don’t add any files now inside build folder as it will automatically add a minified version of your index.js file when run npm build command.
Now, open your package.json file and add the following line inside scripts array.
"build:scripts": "wp-scripts build"
This will simply start building your script when you fire npm run build: scripts command and add a minified version of your index.js file inside build folder which you created previously.
Now, our real work starts. Create following files
index.php You can create this file anywhere you want and include it in your theme’s functions.php file. In index.php file, you need to create one function in which you need to register your script first using
wp_register_script function and add one another function named
register_block_type which contains your namespace as a first parameter and array of scripts as a second parameter.
index.js In js file, you can write code for all the custom blocks you want to add inside default function named registerBlockType. you also need to import some packages from WordPress before you start writing any codes.
After you have written your code for your first custom Gutenberg block then you need to run command for running your script using the following command. npm start-build After running this command your scripts will start building and you can see a message like wp-scripts start as shown in the screenshot below.
Now, open your posts section and click on add block in the left top and search for your custom block. add some content inside it and save it. after saving your post view post and you can see your first custom block there.