Skip to content

Instantly share code, notes, and snippets.

@dan-gamble
Created January 23, 2019 09:56
Show Gist options
  • Save dan-gamble/ee2df1f35672978b0346db865b61c9ee to your computer and use it in GitHub Desktop.
Save dan-gamble/ee2df1f35672978b0346db865b61c9ee to your computer and use it in GitHub Desktop.

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)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment