bud icon indicating copy to clipboard operation
bud copied to clipboard

[bug] dynamic imports doesn't work with extracted WordPress dependencies

Open cawa-93 opened this issue 2 years ago • 3 comments

Agreement

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 = __
  1. Create there two files.
  2. Enqueue index.js into page.
  3. Check console logs.

version

6.20.0

Logs

No response

Configuration

No response

Relevant .budfiles

No response

cawa-93 avatar Jan 12 '24 14:01 cawa-93

Enqueue index.js into page.

How exactly are you doing this? Are you using the bundle function from Acorn?

retlehs avatar Jan 12 '24 15:01 retlehs

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')

зображення

cawa-93 avatar Jan 12 '24 15:01 cawa-93

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

kellymears avatar Jan 18 '24 19:01 kellymears

Message to comment on stale issues. If none provided, will not mark issues stale

github-actions[bot] avatar Mar 19 '24 01:03 github-actions[bot]