no-build-tools-no-problems
no-build-tools-no-problems copied to clipboard
Use import maps for back-compat / future-proof
This would allow us to change imports like this:
const { Card } = wp.components;
...to the ES6 standard:
import { Card } from '@wordpress/element';
Background: https://dev.to/open-wc/on-the-bleeding-edge-3cb8
Shim: https://www.npmjs.com/package/es-module-shims
The mapping itself seems to work in my tests so far, but it doesn't look like the import succeeds.
I get an error when mapping @wordpress/components to /path/to/wp-includes/js/dist/components.js, because that file isn't an ES module, it's just an IIFE. We can't import { foo }... because the IIFE doesn't export foo....
Core could distribute dist/components.esm.js files1, and deprecate the .js files, but that would result in both versions of the file being loaded on some pages, because plugins.
On the other hand, plugins could avoid enqueueing dist/components.js and manually map to an up-converted ES module (e.g., https://cdn.skypack.dev/pin/@wordpress/[email protected]/min/@wordpress/components.js), but that'd have the same problem of both files being loaded.
I don't think import maps will ever provide a way to map to window.wp, since that wouldn't fit the module paradigm. I could be wrong though.
We can still use import maps for 3rd party dependencies in #1, but for Core we might be stuck referencing wp.components?
1: Not using .mjs because Apache/etc might not serve that with the right mime type, etc.
Maybe the existing .js files could be changed to UMD?
~~This is blocked on a Snowpack bug with modules that have an @ symbol in the name.~~
Nevermind, that shouldn't affect this since we'd be mapping to wp-includes, not the plugin's local bundle.
If we do start using import ... @wordpress/..., though, we'll want to add them as externals to snowpack.config.js
Maybe we can use bare imports in the dev workflow, but have them configured as externals and replaced w/ wp.foo in the build files?
Import maps are available by default in Chrome now 🎉
It'll probably still be awhile before other browsers do it, though.
xref https://wordpress.slack.com/archives/C5UNMSU4R/p1615573395194800?thread_ts=1615573177.193800&cid=C5UNMSU4R