diff --git a/packages/block-library/README.md b/packages/block-library/README.md index 92cf2c6a351843..45f923af9f8e3e 100644 --- a/packages/block-library/README.md +++ b/packages/block-library/README.md @@ -14,7 +14,7 @@ _This package assumes that your code will run in an **ES2015+** environment. If ## Building JavaScript for the browser -If a `view.js` file is present in the block's directory, this file will be built along other assets, making it available to load from the browser. +If a `view.js` file (or a file prefixed with `view`, e.g. `view-example.js`) is present in the block's directory, this file will be built along other assets, making it available to load from the browser. This enables us to, for instance, load this file when the block is present on the page in two ways: diff --git a/tools/webpack/blocks.js b/tools/webpack/blocks.js index 11d4635af96324..c9a5af0b631ce1 100644 --- a/tools/webpack/blocks.js +++ b/tools/webpack/blocks.js @@ -17,10 +17,11 @@ const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extrac const { baseConfig, plugins, stylesTransform } = require( './shared' ); /* - * Matches a block's name in paths in the form - * build-module//view.js + * Matches a block's filepaths in the form build-module/.js */ -const blockNameRegex = new RegExp( /(?<=build-module\/).*(?=(\/view))/g ); +const blockViewRegex = new RegExp( + /build-module\/(?.*\/view.*).js$/ +); /** * We need to automatically rename some functions when they are called inside block files, @@ -31,14 +32,14 @@ const prefixFunctions = [ 'build_query_vars_from_query_block' ]; const createEntrypoints = () => { /* - * Returns an array of paths to view.js files within the `@wordpress/block-library` package. - * These paths can be matched by the regex `blockNameRegex` in order to extract - * the block's name. + * Returns an array of paths to block view files within the `@wordpress/block-library` package. + * These paths can be matched by the regex `blockViewRegex` in order to extract + * the block's filename. * * Returns an empty array if no files were found. */ const blockViewScriptPaths = fastGlob.sync( - './packages/block-library/build-module/**/view.js' + './packages/block-library/build-module/**/view*.js' ); /* @@ -46,11 +47,14 @@ const createEntrypoints = () => { * each block's view.js file. */ return blockViewScriptPaths.reduce( ( entries, scriptPath ) => { - const [ blockName ] = scriptPath.match( blockNameRegex ); + const result = scriptPath.match( blockViewRegex ); + if ( ! result?.groups?.filename ) { + return entries; + } return { ...entries, - [ 'blocks/' + blockName ]: scriptPath, + [ result.groups.filename ]: scriptPath, }; }, {} ); }; @@ -61,7 +65,7 @@ module.exports = { entry: createEntrypoints(), output: { devtoolNamespace: 'wp', - filename: './build/block-library/[name]/view.min.js', + filename: './build/block-library/blocks/[name].min.js', path: join( __dirname, '..', '..' ), }, plugins: [