Skip to content

Instantly share code, notes, and snippets.

@socheatsok78
Last active October 27, 2022 08:11
Show Gist options
  • Save socheatsok78/df11e52b1ea8be491c450940d20b443a to your computer and use it in GitHub Desktop.
Save socheatsok78/df11e52b1ea8be491c450940d20b443a to your computer and use it in GitHub Desktop.
A collection of useful Webpack `require.context` loaders.
// bootstrap.js
export function WebpackConfigLoader () {
const r = require.context('@/configs', false, /\.js$/, 'lazy')
const modules = WebpackRequireContextWrapper(r)
return ConfigurationLoader(modules)
}
// ConfigurationLoader.js
export function ConfigurationLoader (modules) {
return new Promise((resolve) => {
const _promiseChains = []
const configs = {}
for (const path in modules) {
const name = path.replace('./', '').split('.')[0]
_promiseChains.push(modules[path]())
modules[path]()
.catch(() => {
configs[name] = {}
})
.then((mod) => {
const value = ('default' in mod) ? mod.default : mod
configs[name] = value
})
}
Promise.allSettled(_promiseChains).then(() => resolve(configs))
})
}
// bootstrap.js
export function WebpackLocaleLoader () {
const r = require.context('@/locales', true, /\.js$/, 'lazy')
const modules = WebpackRequireContextWrapper(r)
return LocalizationLoader(modules)
}
// LocalizationLoader.js
export function LocalizationLoader (modules) {
return new Promise((resolve) => {
const _promiseChains = []
const locales = {}
for (const path in modules) {
const fragment = path.replace('./', '').split('.')[0]
const [locale, name] = fragment.split('/')
locales[locale] = (locales[locale] || {})
_promiseChains.push(modules[path]())
modules[path]()
.catch(() => {
locales[locale][name] = {}
})
.then((mod) => {
const value = ('default' in mod) ? mod.default : mod
locales[locale][name] = value
})
}
Promise.allSettled(_promiseChains).then(() => resolve(locales))
})
}
/**
* A glob import wrapper for Webpack's `require.context`.
* @example
* const r = require.context('./dir', false, /\.js$/, 'lazy')
* const modules = WebpackRequireContextWrapper(r)
* // Output
* const modules = {
* './foo.js': () => import('./foo.js'),
* './bar.js': () => import('./bar.js'
* }
*/
export function WebpackRequireContextWrapper (r) {
const modules = {}
for (const k of r.keys()) {
modules[k] = () => r(k)
}
return modules
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment