There are a couple of version of this.
This is a basic one that doesn't actually create new bundles but prevents all of the function importing and calling.
entry-file.js
document.addEventListener('DOMContentLoaded', () => {
...
getElements('[data-module]').forEach(el => {
const modules = el
.getAttribute('data-module')
.split(',')
.map(name => name.trim())
modules.forEach(module => {
const Module = require(`../modules/${module}`).default
new Module(el)
})
})
})
template.html
<section class="hd-Header" data-module="header, header-notification, sticky-header">
This is a tasty one that creates a new entry point for each module that allows for true code splitting:
webpack.config.js
const fs = require('fs')
const path = require('path')
const entrypoints = {}
// Module entrypoints
fs.readdirSync(path.join('path', 'to', 'modules', 'folder')).forEach(file => {
const name = path.parse(file).name
const jsFile = path.join(
'path',
'to',
'modules',
`${name}.js`
)
if (fs.existsSync(jsFile)) {
entrypoints[`module.${name}`] = jsFile
}
})
entry-point.js
async function loadModule (name) {
return await import(/* webpackChunkName: name */ `module.${name}`)
}
getElements('[data-module]').forEach(async el => {
const name = el.getAttribute('data-module')
const module = await loadModule(name)
new module (el)
})