Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created December 23, 2019 14:27
Show Gist options
  • Save hawkeye64/1b65070b5d75c998b2a8b3caa3d3cb73 to your computer and use it in GitHub Desktop.
Save hawkeye64/1b65070b5d75c998b2a8b3caa3d3cb73 to your computer and use it in GitHub Desktop.
Dynamically load Vue components from a folder
export default ({ Vue }) => {
const examples = require('../assets/examples').default
for (const index in examples) {
import(
/* webpackChunkName: "examples" */
/* webpackMode: "lazy-once" */
`../examples/${examples[index].file}.vue`
).then(comp => {
Vue.component(examples[index].file, comp.default)
})
}
}
@hawkeye64
Copy link
Author

assets/examples.js goes like this:

function kebabCase (str) {
  const result = str.replace(
    /[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g,
    match => '-' + match.toLowerCase()
  )
  return (str[0] === str[0].toUpperCase())
    ? result.substring(1)
    : result
}

function slugify (str) {
  return encodeURIComponent(String(str).trim().replace(/\s+/g, '-'))
}

export default require.context('../examples', true, /^\.\/.*\.vue$/)
  .keys()
  .map(page => page.slice(2).replace('.vue', ''))
  .filter(page => page !== 'Index')
  .map(page => ({
    file: page,
    title: page + '.vue',
    path: slugify(kebabCase(page))
  }))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment