
By default, when you use @wordpress/scripts dependency to build scripts using:
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start"
},
in package.json or if you’re just started with block and following the create a block tutorial, you’ll find it uses @wordpress/scripts.
With @wordpress/scripts
, the files need to be in your-plugin/src
directory and the build with the command npm run build
will be generated in your-plugin/build
folder.
The src folder basically contains index.js, edit.js, save.js, editor.scss, style.scss
and build contains index.asset.php, index.css, index.js, style-index.css
.
However, you might not want the same folder structure. That is the src
and build
folder to be in the plugin’s root directory.
How to customize src/build folders?
The default webpack.config
bundled by @wordpress/scripts
is setting these folders src/build
as default. To customize the path of these folders or rename these folders, we’ll need the separate webpack.config.js file within the plugin’s root directory. So, your-plugin/webpack.config.js
/**
* External Dependencies
*/
const path = require( 'path' );
/**
* WordPress Dependencies
*/
const defaultConfig = require( '@wordpress/scripts/config/webpack.config.js' );
module.exports = {
...defaultConfig,
entry: {
index: path.resolve( __dirname, 'assets/src', 'index.js' ),
},
output: {
path: path.resolve( __dirname, 'assets/build' ),
},
}
Using this webpack config, the src and build folders will move into assets/src
and assets/build
folder. After all, these are the assets.
So, the new paths would be: your-plugin/assets/src
, and your-plugin/assets/build
. Of course, you can rename the folder or change the folder path, just look at the entry and output section of the webpack config.
The easier way
If you only want to change the location of the src/
and /build
directories, you can simply write that in package.json
file without the need of webpack.config.js
.
"scripts": {
"build": "wp-scripts build assets/src/index.js --output-path=assets/build",
},
Hey Sanjeev,
Your blog help me put in the right direction, but this code only works if there is only one block inside the src folder, if the directory structure was like this.
-src
–block-1
—block.json
–block-2
—block.json
this would fail, as it is looking for index.js in src which is not preset, you can define multiple entry points in webpack file, but it is better to use –webpack-src-dir flag for it.
by default @wordpress/scrips looks for all the subdirectories ref: https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/#:~:text=When%20using%20the,src%2Ddir%20flag.
you can use –webpack-src-dir like this,
“build”: “wp-scripts build –webpack-src-dir=custom-src-folder/src –output-path=custom-build-folder/build”,
,
Now I wanted to ask if there is any way to do this using webpack.config file, as I cannot figure this out myself.
Hi Juzar – thanks for reaching out. Unfortunately, I’m also not sure how that works. Sorry : (