[bug] dynamic imports doesn't work with extracted WordPress dependencies
Agreement
- [X] This is not a duplicate of an existing issue
- [X] I have read the guidelines for Contributing to Roots Projects
- [X] This is not a personal support request that should be posted on the Roots Discourse community
Describe the issue
If I dynamically import a module that includes import of WP dependencies, this module is loaded without WP dependencies.
Expected Behavior
The dependencies of the WP are dynamically loaded and initialize global variables before the main module is executed.
Actual Behavior
Wordpress dependencies are extracted but not dynamically loaded when the module is loaded.
Steps To Reproduce
// index.js
const {getText} = await import('./translator.js')
console.log( getText )
// translator.js
import { __ } from '@wordpress/i18n';
export const getText = __
- Create there two files.
- Enqueue index.js into page.
- Check console logs.
version
6.20.0
Logs
No response
Configuration
No response
Relevant .budfiles
No response
Enqueue index.js into page.
How exactly are you doing this? Are you using the bundle function from Acorn?
We use the bedrock and sage theme.
In theme's setup.php
add_action('wp_enqueue_scripts', function () {
bundle('category')->enqueue();
}, 100);
The problem occurs in development mode. The development mode is launched with a bud dev. On page I got error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'i18n')
I haven't looked at this super closely yet but at first glance:
you can't dynamically import WordPress dependencies as they are included via window variables.
As in, your source:
import { __ } from '@wordpress/i18n'
compiles to something like:
const __ = wp.i18n.__
window.wp is set by WordPress core via acorn.
I've never tried to dynamically import WP dependencies because of this reason and while it would be nice if it worked, it seems that it doesn't. This might be an improvement that we can make to @roots/wordpress-dependencies-webpack-plugin and/or @roots/wordpress-externals-webpack-plugin but it might also be an upstream limitation in webpack itself.
As a workaround I would add any import statements to the entrypoint so that they are properly picked up on by the plugins.
Example for an entrypoint called app.js which uses @wordpress/i18n somewhere via a dynamic import:
import '@wordpress/i18n' // flag external pkg
// ... your source
Message to comment on stale issues. If none provided, will not mark issues stale