タイトルのまんまです。 require.context
を利用して、或るディレクトリ配下にあるコンポーネントファイル(.vue)をまるっとrequireしたい。
エントリーファイル(main.js)に次のように記述します。
function requireAll (context) {
const components = {}
context.keys().forEach((_path) => {
const name = _path.split('/')
.filter((s) => !/^\./.test(s))
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
.join('')
.replace(/\.vue$/, '')
components[name] = context(_path).default
})
return components
}
const components = requireAll(require.context('./pages', true, /\.vue$/))
components
にはパス名がPascalCaseされた名前をキーにしたコンポーネントが格納されるので、あとは環境にあわせて煮るなり焼くなり好きにしましょう。
new Vue({
el: '#app',
components
})
プロジェクトの都合でnuxtを導入できなかったりする時などに出番があるやもしれません。