Skip to content

Instantly share code, notes, and snippets.

@Accudio
Created September 25, 2024 14:02
Show Gist options
  • Save Accudio/35e17148732e7c26400a2d70e4dbf3b0 to your computer and use it in GitHub Desktop.
Save Accudio/35e17148732e7c26400a2d70e4dbf3b0 to your computer and use it in GitHub Desktop.
Shopify + Laravel Mix + Async Alpine for dynamic imports
/**
* This is added to your `main.js` file, the one that imports and runs Async Alpine. Make sure that
* it runs before any `import()` functions by putting as high as possible. That may mean adding it to
* a static import if your other static imports dynamically import immediately.
*/
__webpack_public_path__ = window.assetsPath;
/**
* If you want to automatically register all components within a certain directory as async, you can do
* that with `require.context()` and the fourth param as 'weak'. Add this to your main.js file and
* Webpack will compile it down into importing every JS file within the `async/` directory
*/
const components = require.context(`./async/`, true, /\.js$/i, 'weak');
components.keys().map((key) => {
const name = key.split("/").pop().split(".")[0];
Alpine.asyncData(name, () => import(`./async/${name}.js`))
});
{% comment %}
Put this script within your theme.liquid — or wherever you load your JS —
to provide the asset URLs to Webpack for dynamic imports.
Make sure it runs before your JS does by putting it before in the DOM.
{% endcomment %}
<script>window.assetsPath="{{ 'main.min.js' | asset_url | split: 'assets/' | first }}"</script>
/**
* Add this to your mix configuration file at some point to make sure dynamically-imported
* chunks are output correctly. If you're already using `webpackConfig()`, merge the objects.
*/
mix.webpackConfig({
output: {
chunkFilename: 'assets/[name].chunk.js',
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment