-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_elements-rails.js
22 lines (22 loc) · 990 Bytes
/
custom_elements-rails.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export function eagerDefineCustomElementsFrom(namespace, options = {}) {
const pathToElementName = (path) => {
const parts = path.split('/').map(p => p.replace(/_/g, '-'));
return `${options.prefix}-${parts.slice(0, -1).join('--')}${parts.length > 1 ? '--' : ''}${parts.at(-1)}`;
}
const importmap = document.querySelector('script[type="importmap"]')
const { imports } = JSON.parse(importmap.textContent)
const regex = new RegExp(`${namespace}/(.*?)[-_]element`)
Object.entries(imports)
.filter(([name, _]) => name.match(regex) )
.map(([name, importPath]) => { return [pathToElementName(name.match(regex)[1]), importPath] })
.forEach(([name, importPath]) => {
import(importPath)
.then((module) => {
customElements.define(name, module.default)
})
.catch((error) => {
console.error(`custom_elements-rails: Could not import custom element <${options.prefix}-${name}>`)
throw error
})
})
}