Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions packages/dependency-extraction-webpack-plugin/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

## Unreleased

### Breaking Changes

- Require webpack 5.95.0 or newer ([#87098](https://github.com/WordPress/gutenberg/pull/87098)).
- `defaultRequestToExternalModule`, exported from `lib/util`, returns script module IDs without an externals type prefix ([#87098](https://github.com/WordPress/gutenberg/pull/87098)).

### Enhancements

- Keep the kind of each import of an externalized script module in script module builds: a static `import` stays static and an `import()` stays dynamic, `@wordpress/interactivity` included ([#87098](https://github.com/WordPress/gutenberg/pull/87098)).

## 7.2.0 (2026-11-18)

### Enhancements
Expand Down
20 changes: 11 additions & 9 deletions packages/dependency-extraction-webpack-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Install the module
npm install @wordpress/dependency-extraction-webpack-plugin --save-dev
```

**Note**: This package requires Node.js version with long-term support status (check [Active LTS or Maintenance LTS releases](https://nodejs.org/en/about/previous-releases)). It also requires webpack 5.0.0 or newer. It is not compatible with older versions.
**Note**: This package requires Node.js version with long-term support status (check [Active LTS or Maintenance LTS releases](https://nodejs.org/en/about/previous-releases)). It also requires webpack 5.95.0 or newer. It is not compatible with older versions.

## Usage

Expand Down Expand Up @@ -68,7 +68,7 @@ The asset file name mirrors the emitted JavaScript file name, replacing the file

For example, for an entry named `entrypoint`:

```
```text
// Entry `entrypoint`
import { Component } from 'react';

Expand Down Expand Up @@ -138,7 +138,7 @@ Each entry point in the webpack bundle will include an asset file that declares

For example, for an entry named `entrypoint`:

```
```text
// Entry `entrypoint`
import { store, getContext } from '@wordpress/interactivity';

Expand All @@ -152,11 +152,13 @@ import { store, getContext } from '@wordpress/interactivity';

By default, the following script module requests are handled:

| Request |
| ---------------------------- |
| `@wordpress/interactivity ` |
| Request |
| --------------------------------- |
| `@wordpress/a11y` |
| `@wordpress/interactivity` |
| `@wordpress/interactivity-router` |

(`@wordpress/interactivity` is currently the only available WordPress script module.)
Imports of an externalized script module keep their kind in the bundle: a static `import` declaration stays a static import, and an `import()` stays an `import()` of the script module, which loads it when that code runs.

**Note:** This plugin overlaps with the functionality provided by [webpack `externals`](https://webpack.js.org/configuration/externals). This plugin is intended to extract script module identifiers from bundle compilation so that a list of script module dependencies does not need to be manually maintained. If you don't need to extract a list of script module dependencies, use the `externals` option directly.

Expand Down Expand Up @@ -228,7 +230,7 @@ You can provide a filename, or set it to `true` to report to a default `external

##### `requestToExternal`

**Note**: This option is not available with script modules. See [`requestToExternalModule`](#requestToExternalModule) for module usage.
**Note**: This option is not available with script modules. See [`requestToExternalModule`](#requesttoexternalmodule) for module usage.

- Type: function

Expand Down Expand Up @@ -259,7 +261,7 @@ module.exports = {

##### `requestToExternalModule`

**Note**: This option is only available with script modules. See [`requestToExternal`](#requestToExternal) for script usage.
**Note**: This option is only available with script modules. See [`requestToExternal`](#requesttoexternal) for script usage.

- Type: function

Expand Down
154 changes: 117 additions & 37 deletions packages/dependency-extraction-webpack-plugin/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,42 +56,56 @@ class DependencyExtractionWebpackPlugin {
}

/**
* @param {webpack.ExternalItemFunctionData} data
* @param { ( err?: null | Error, result?: string | string[] ) => void } callback
* Map a request to the external that the plugin externalizes it to.
*
* @param {string} request Requested module.
* @return {string|string[]|undefined} The external, or `undefined` when the
* plugin does not externalize the request.
* @throws {Error} When the request can't be used, like a WordPress script in a script module.
*/
externalizeWpDeps( { request }, callback ) {
mapRequestToExternal( request ) {
let externalRequest;

try {
// Handle via options.requestToExternal(Module) first.
if ( this.useModules ) {
if (
typeof this.options.requestToExternalModule === 'function'
) {
externalRequest =
this.options.requestToExternalModule( request );
// Handle via options.requestToExternal(Module) first.
if ( this.useModules ) {
if ( typeof this.options.requestToExternalModule === 'function' ) {
externalRequest =
this.options.requestToExternalModule( request );

// requestToExternalModule allows a boolean shorthand
if ( externalRequest === false ) {
externalRequest = undefined;
}
if ( externalRequest === true ) {
externalRequest = request;
}
// requestToExternalModule allows a boolean shorthand
if ( externalRequest === false ) {
externalRequest = undefined;
}
if ( externalRequest === true ) {
externalRequest = request;
}
} else if ( typeof this.options.requestToExternal === 'function' ) {
externalRequest = this.options.requestToExternal( request );
}
} else if ( typeof this.options.requestToExternal === 'function' ) {
externalRequest = this.options.requestToExternal( request );
}

// Cascade to default if unhandled and enabled.
if (
typeof externalRequest === 'undefined' &&
this.options.useDefaults
) {
externalRequest = this.useModules
? defaultRequestToExternalModule( request )
: defaultRequestToExternal( request );
}
// Cascade to default if unhandled and enabled.
if (
typeof externalRequest === 'undefined' &&
this.options.useDefaults
) {
externalRequest = this.useModules
? defaultRequestToExternalModule( request )
: defaultRequestToExternal( request );
}

return externalRequest;
}

/**
* @param {webpack.ExternalItemFunctionData} data
* @param { ( err?: null | Error, result?: string | string[] ) => void } callback
*/
externalizeWpDeps( { request }, callback ) {
let externalRequest;

try {
externalRequest = this.mapRequestToExternal( request );
} catch ( err ) {
return callback( err );
}
Expand All @@ -105,6 +119,63 @@ class DependencyExtractionWebpackPlugin {
return callback();
}

/**
* Keep each `import()` of an externalized request in a module apart from
* the module's static imports of the same request.
*
* Webpack externalizes the dependencies of one module that share a
* resource identifier together, with the kind of the first one, so a
* static import and an `import()` of one request would get one kind.
* Giving the `import()` its own resource identifier makes webpack
* externalize it on its own, with the dynamic kind. The dependency keeps
* that identifier when a rebuild reuses the module from the memory cache.
*
* A `webpackMode: "weak"` `import()` stays with the static imports: on its
* own, it would point to an external that no chunk loads, so it would
* always reject. Grouped, it comes first, so the group, the file's static
* imports of the request included, gets the dynamic kind.
*
* @param {webpack.Module} module Module whose dependencies webpack is about to resolve.
*/
separateDynamicImports( module ) {
const blocks = [ module ];
while ( blocks.length ) {
const block = blocks.pop();
blocks.push( ...block.blocks );

for ( const dependency of block.dependencies ) {
// Webpack types the dependency of an `import()` of a string as
// `import()`, or as `import() eager` in eager mode, where the
// module holds it instead of an async block.
if (
! [ 'import()', 'import() eager' ].includes(
dependency.type
) ||
! this.isExternalized( dependency.request )
) {
continue;
}

const resourceIdentifier = dependency.getResourceIdentifier();
dependency.getResourceIdentifier = () =>
`${ resourceIdentifier }|import()`;
}
}
}

/**
* @param {string} request Requested module.
* @return {boolean} Whether the plugin externalizes the request.
*/
isExternalized( request ) {
try {
return Boolean( this.mapRequestToExternal( request ) );
} catch {
// Webpack reports the error when it resolves the request.
return false;
}
}

/**
* @param {string} request
* @return {string} Mapped dependency name
Expand Down Expand Up @@ -156,10 +227,15 @@ class DependencyExtractionWebpackPlugin {

/**
* Offload externalization work to the ExternalsPlugin.
*
* Script modules use the `module-import` type, so a static `import`
* declaration of an external stays static and an `import()` of it stays
* dynamic (see `separateDynamicImports` for a file that has both).
*
* @type {webpack.ExternalsPlugin}
*/
this.externalsPlugin = new webpack.ExternalsPlugin(
this.useModules ? 'import' : 'window',
this.useModules ? 'module-import' : 'window',
this.externalizeWpDeps.bind( this )
);

Expand All @@ -168,6 +244,15 @@ class DependencyExtractionWebpackPlugin {
compiler.hooks.thisCompilation.tap(
this.constructor.name,
( compilation ) => {
if ( this.useModules ) {
// Runs after webpack parses a module and before it resolves
// the module's dependencies.
compilation.hooks.succeedModule.tap(
this.constructor.name,
( module ) => this.separateDynamicImports( module )
);
}

compilation.hooks.processAssets.tap(
{
name: this.constructor.name,
Expand Down Expand Up @@ -337,13 +422,6 @@ class DependencyExtractionWebpackPlugin {
const { userRequest } = m;
if ( this.externalizedDeps.has( userRequest ) ) {
if ( this.useModules ) {
// A static occurrence (in the entry chunk) wins.
if (
fromAsyncChunk &&
chunkStaticDeps.has( m.request )
) {
return;
}
// Externals in an async chunk are reached via a dynamic
// import by definition.
const isStatic =
Expand Down Expand Up @@ -466,6 +544,8 @@ class DependencyExtractionWebpackPlugin {
// Sort these so we can produce a stable, stringified representation.
...Array.from( chunkStaticDeps ).sort(),
...Array.from( chunkDynamicDeps )
// A static occurrence of a script module wins.
.filter( ( id ) => ! chunkStaticDeps.has( id ) )
.sort()
.map( ( id ) => ( { id, import: 'dynamic' } ) ),
],
Expand Down
22 changes: 8 additions & 14 deletions packages/dependency-extraction-webpack-plugin/lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,32 +76,26 @@ function defaultRequestToExternal( request ) {
/**
* Default request to external module transformation
*
* Currently only `@wordpress/interactivity` and `@wordpress/interactivity-router`
* are supported.
* Currently only `@wordpress/interactivity`, `@wordpress/interactivity-router`,
* and `@wordpress/a11y` are supported. Each maps to its own script module ID,
* without an externals type, so each import of it takes its kind from the
* plugin's externals type.
*
* Do not use the boolean shorthand here, it's only handled for the
* `requestToExternalModule` option.
*
* @param {string} request Module request (the module name in `import from`) to be transformed
* @return {string|Error|undefined} The resulting external definition.
* @return {string|undefined} The resulting external definition.
* - Return `undefined` to ignore the request (do not externalize).
* - Return `string` to map the request to an external.
* - Return `Error` to emit an error.
* @throws {Error} When the request is a WordPress script, which script modules can't import.
*/
function defaultRequestToExternalModule( request ) {
if ( request === '@wordpress/interactivity' ) {
// This is a special case. Interactivity does not support dynamic imports at
// this time. We add the external "module" type to indicate that webpack
// should externalize this as a module (instead of our default `import()`
// external type) which forces @wordpress/interactivity imports to be
// hoisted to static imports.
return `module ${ request }`;
}

switch ( request ) {
case '@wordpress/interactivity':
case '@wordpress/interactivity-router':
case '@wordpress/a11y':
return `import ${ request }`;
return request;
}

const isWordPressScript = Boolean( defaultRequestToExternal( request ) );
Expand Down
2 changes: 1 addition & 1 deletion packages/dependency-extraction-webpack-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"webpack": "^5.111.0"
},
"peerDependencies": {
"webpack": "^5.0.0"
"webpack": "^5.95.0"
},
"publishConfig": {
"access": "public"
Expand Down
Loading
Loading