Recommended way of including header scripts in build process? #60
-
I'm using Alpine.js to create components for my store. I'm wondering if there is a recommended clean way of adding global functions to be loaded in the header other than just creating a scripts snippet for the header and adding my JS there. Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi 👋, here's an example based on a dropdown component:
export default {
name: 'dropdown',
component () {
return {
show: false,
open() { this.show = true },
close() { this.show = false },
isOpen() { return this.show === true }
}
}
}
<div x-data="dropdown()">
<button x-on:click="open">Open</button>
<div x-show="isOpen()" x-on:click.away="close">
// Dropdown
</div>
</div>
/**
* imports
*/
import 'alpinejs'
import './css/main.css'
/**
* auto-import all alpine components
*/
const alpineComponents = require.context('./alpine/', true, /\.js$/)
alpineComponents.keys().forEach(key => {
const component = alpineComponents(key).default
// if a component has a name defined use the name, else use the path as the component name
const name = component.name
? component.name
: key.replace(/\.(\/|js)/g, '').replace(/(\/|-|_|\s)\w/g, (match) => match.slice(1).toUpperCase())
window[name] = component.component
}) if you provide a name inside your component, you can reference it by the name. Otherwise, the file path will be transformed to |
Beta Was this translation helpful? Give feedback.
Hi 👋,
here's an example based on a dropdown component:
alpine
directory in your source foldersrc/alpine
dropdown.js
in your alpine directorysrc/alpine/dropdown.js
with the following content:.liquid
file:src/main.js
file should look something like the follo…