Skip to content

Commit f3ad70f

Browse files
fullofcaffeinejsnajdrgziolo
authored
Generate minified .min.js and unminified .js files for GB js entry points when building (WordPress#31732)
* Add .min.js suffix to index script depending on the presence of env var and enqueue .min.js files by default in `client-assets.php` * Decide what to enqueue depending on the value of the SCRIPT_DEBUG env var - If set and true, we enqueue the unminified index.js file for the given package; - If not set or set and false, we enqueue the minified (production) index.min.js file. * WIP * Save unminified .js sources before minimizer runs * No need to pass the mode anymore * Add packaged version PoC and tests * Package as internal monorepo npm, remove top-level PoC module * Add test artifacts * Use snake case for var, simplify and DRY the asset name * Hardcode index.min.js for override scripts * Always refer to index.asset.php as the asset loader scripts The WebPack build generates them using the `index.asset.php` name format. * More reliable extension replacement * Fix lint error * Fix php lint errors * Fix another linter error (prefer-alphabetical-devDependencies) * Update packages/readable-js-assets-webpack-plugin/package.json Change the plugin version to include a '-prerelease' suffix. Co-authored-by: Greg Ziółkowski <grzegorz@gziolo.pl> * Update packages/readable-js-assets-webpack-plugin/README.md Fix webpack spelling :) Co-authored-by: Greg Ziółkowski <grzegorz@gziolo.pl> * Add .nmprc and CHANGELOG.md * Restrict the compressed-size-action to *.min.js assets (and *.css) Co-authored-by: Jarda Snajdr <jsnajdr@gmail.com> Co-authored-by: Greg Ziółkowski <grzegorz@gziolo.pl>
1 parent 840031e commit f3ad70f

File tree

20 files changed

+501
-9
lines changed

20 files changed

+501
-9
lines changed

.github/workflows/bundle-size.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,4 @@ jobs:
5858
- uses: preactjs/compressed-size-action@7d87f60a6b0c7d193b8183ce859ed00b356ea92f # v2.1.0
5959
with:
6060
repo-token: '${{ secrets.GITHUB_TOKEN }}'
61-
pattern: '{build/**/*.js,build/**/*.css}'
61+
pattern: '{build/**/*.min.js,build/**/*.css}'

docs/manifest.json

+6
Original file line numberDiff line numberDiff line change
@@ -1727,6 +1727,12 @@
17271727
"markdown_source": "../packages/react-native-editor/README.md",
17281728
"parent": "packages"
17291729
},
1730+
{
1731+
"title": "@wordpress/readable-js-assets-webpack-plugin",
1732+
"slug": "packages-readable-js-assets-webpack-plugin",
1733+
"markdown_source": "../packages/readable-js-assets-webpack-plugin/README.md",
1734+
"parent": "packages"
1735+
},
17301736
{
17311737
"title": "@wordpress/redux-routine",
17321738
"slug": "packages-redux-routine",

lib/client-assets.php

+6-5
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ function gutenberg_override_translation_file( $file, $handle ) {
127127
}
128128

129129
// Ignore scripts that are not found in the expected `build/` location.
130-
$script_path = gutenberg_dir_path() . 'build/' . substr( $handle, 3 ) . '/index.js';
130+
$script_path = gutenberg_dir_path() . 'build/' . substr( $handle, 3 ) . '/index.min.js';
131131
if ( ! file_exists( $script_path ) ) {
132132
return $file;
133133
}
@@ -236,14 +236,15 @@ function gutenberg_register_packages_scripts( $scripts ) {
236236
// When in production, use the plugin's version as the default asset version;
237237
// else (for development or test) default to use the current time.
238238
$default_version = defined( 'GUTENBERG_VERSION' ) && ! ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? GUTENBERG_VERSION : time();
239+
$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '.js' : '.min.js';
239240

240-
foreach ( glob( gutenberg_dir_path() . 'build/*/index.js' ) as $path ) {
241+
foreach ( glob( gutenberg_dir_path() . "build/*/index$suffix" ) as $path ) {
241242
// Prefix `wp-` to package directory to get script handle.
242-
// For example, `…/build/a11y/index.js` becomes `wp-a11y`.
243+
// For example, `…/build/a11y/index.min.js` becomes `wp-a11y`.
243244
$handle = 'wp-' . basename( dirname( $path ) );
244245

245-
// Replace `.js` extension with `.asset.php` to find the generated dependencies file.
246-
$asset_file = substr( $path, 0, -3 ) . '.asset.php';
246+
// Replace suffix and extension with `.asset.php` to find the generated dependencies file.
247+
$asset_file = substr( $path, 0, -( strlen( $suffix ) ) ) . '.asset.php';
247248
$asset = file_exists( $asset_file )
248249
? require( $asset_file )
249250
: null;

package-lock.json

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@
141141
"@wordpress/postcss-themes": "file:packages/postcss-themes",
142142
"@wordpress/prettier-config": "file:packages/prettier-config",
143143
"@wordpress/project-management-automation": "file:packages/project-management-automation",
144+
"@wordpress/readable-js-assets-webpack-plugin": "file:packages/readable-js-assets-webpack-plugin",
144145
"@wordpress/scripts": "file:packages/scripts",
145146
"@wordpress/stylelint-config": "file:packages/stylelint-config",
146147
"appium": "1.20.2",

packages/dependency-extraction-webpack-plugin/lib/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ class DependencyExtractionWebpackPlugin {
179179
}
180180

181181
const assetFilename = buildFilename.replace(
182-
/\.js$/i,
182+
/(\.min)?\.js$/i,
183183
'.asset.' + ( outputFormat === 'php' ? 'php' : 'json' )
184184
);
185185

packages/dependency-extraction-webpack-plugin/test/__snapshots__/build.js.snap

+20
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,26 @@ Array [
6868
]
6969
`;
7070

71+
exports[`Webpack \`has-extension-suffix\` should produce expected output: Asset file should match snapshot 1`] = `"<?php return array('dependencies' => array('lodash', 'wp-blob'), 'version' => '99bd32161d8514cc8c0cb8b0543ace3f');"`;
72+
73+
exports[`Webpack \`has-extension-suffix\` should produce expected output: External modules should match snapshot 1`] = `
74+
Array [
75+
Object {
76+
"externalType": "window",
77+
"request": "lodash",
78+
"userRequest": "lodash",
79+
},
80+
Object {
81+
"externalType": "window",
82+
"request": Array [
83+
"wp",
84+
"blob",
85+
],
86+
"userRequest": "@wordpress/blob",
87+
},
88+
]
89+
`;
90+
7191
exports[`Webpack \`no-default\` should produce expected output: Asset file should match snapshot 1`] = `"<?php return array('dependencies' => array(), 'version' => '7cedfbba436728640c2c4961b598ab32');"`;
7292

7393
exports[`Webpack \`no-default\` should produce expected output: External modules should match snapshot 1`] = `Array []`;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* External dependencies
3+
*/
4+
import { isEmpty } from 'lodash';
5+
6+
/**
7+
* WordPress dependencies
8+
*/
9+
import { isBlobURL } from '@wordpress/blob';
10+
11+
isEmpty( isBlobURL( '' ) );
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* Internal dependencies
3+
*/
4+
const DependencyExtractionWebpackPlugin = require( '../../..' );
5+
6+
module.exports = {
7+
output: {
8+
filename: 'index.min.js',
9+
},
10+
plugins: [ new DependencyExtractionWebpackPlugin() ],
11+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package-lock=false
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<!-- Learn how to maintain this file at https://github.com/WordPress/gutenberg/tree/HEAD/packages#maintaining-changelogs. -->
2+
3+
## Unreleased
4+
5+
Initial release.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Readable JS assets WebPack Plugin
2+
3+
Generate a readable non-minified JS file for each `.min.js` asset.
4+
5+
The end result is that for each JS entrypoint, we get a set of readable and non-minimized `.js` file and a minimized `.min.js`. This allows Gutenberg to follow the WordPress convention of adding a `.min.js` suffix to minimized JS files, while still providing a readable and unminized files that play well with the WordPress i18n machinery.
6+
7+
Consult the [webpack website](https://webpack.js.org) for additional information on webpack concepts.
8+
9+
## Installation
10+
11+
Install the module
12+
13+
```bash
14+
npm install @wordpress/readable-js-assets-webpack-plugin --save-dev
15+
```
16+
17+
**Note**: This package requires Node.js 12.0.0 or later. It also requires webpack 4.8.3 and newer. It is not compatible with older versions.
18+
19+
## Usage
20+
21+
### Webpack
22+
23+
Use this plugin as you would other webpack plugins:
24+
25+
```js
26+
// webpack.config.js
27+
const ReadableJsAssetsWebpackPlugin = require( '@wordpress/readable-js-assets-webpack-plugin' );
28+
29+
module.exports = {
30+
// …snip
31+
plugins: [ new ReadableJsAssetsWebpackPlugin() ],
32+
};
33+
```
34+
35+
**Note:**
36+
- Multiple instances of the plugin are not supported and may produced unexpected results;
37+
- It assumes your webpack pipeline is already generating a `.min.js` JS asset file for each JS entry-point.
38+
39+
<br/><br/><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* External dependencies
3+
*/
4+
const fs = require( 'fs' );
5+
const path = require( 'path' );
6+
7+
class AddReadableJsAssetsWebpackPlugin {
8+
extractUnminifiedFiles( compilation ) {
9+
const files = compilation.chunks.flatMap( ( chunk ) => chunk.files );
10+
compilation.unminifiedAssets = files.map( ( file ) => {
11+
const asset = compilation.assets[ file ];
12+
const unminifiedFile = file.replace( /\.min\.js$/, '.js' );
13+
return [ unminifiedFile, asset.source() ];
14+
} );
15+
}
16+
async writeUnminifiedFiles( compilation ) {
17+
for ( const [ file, source ] of compilation.unminifiedAssets ) {
18+
await fs.promises.writeFile(
19+
path.join( compilation.options.output.path, file ),
20+
source
21+
);
22+
}
23+
}
24+
apply( compiler ) {
25+
compiler.hooks.compilation.tap(
26+
this.constructor.name,
27+
( compilation ) => {
28+
compilation.hooks.additionalAssets.tap(
29+
this.constructor.name,
30+
() => this.extractUnminifiedFiles( compilation )
31+
);
32+
}
33+
);
34+
compiler.hooks.afterEmit.tapPromise(
35+
this.constructor.name,
36+
( compilation ) => this.writeUnminifiedFiles( compilation )
37+
);
38+
}
39+
}
40+
41+
module.exports = AddReadableJsAssetsWebpackPlugin;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
{
2+
"name": "@wordpress/readable-js-assets-webpack-plugin",
3+
"version": "1.0.0-prerelease",
4+
"description": "Generate a readable JS file for each JS asset.",
5+
"author": "The WordPress Contributors",
6+
"license": "GPL-2.0-or-later",
7+
"keywords": [
8+
"wordpress",
9+
"gutenberg",
10+
"webpack",
11+
"readable",
12+
"minimizer"
13+
],
14+
"homepage": "https://github.com/WordPress/gutenberg/tree/HEAD/packages/readable-js-assets-webpack-plugin/README.md",
15+
"repository": {
16+
"type": "git",
17+
"url": "https://github.com/WordPress/gutenberg.git",
18+
"directory": "packages/readable-js-assets-webpack-plugin"
19+
},
20+
"bugs": {
21+
"url": "https://github.com/WordPress/gutenberg/issues"
22+
},
23+
"engines": {
24+
"node": ">=12.0"
25+
},
26+
"files": [
27+
"index.js"
28+
],
29+
"main": "index.js",
30+
"peerDependencies": {
31+
"webpack": "^4.8.3 || ^5.0.0"
32+
},
33+
"publishConfig": {
34+
"access": "public"
35+
}
36+
}

0 commit comments

Comments
 (0)