Skip to main content

[JavaScript] 모듈 동적 로딩

· One min read

Example1

const requireModule = require.context('.', true, /\.js$/);
const locales = {};

requireModule.keys().forEach((fileName) => {
if (fileName === './index.js') return;

const path = fileName.replace(/(\.\/|\.js)/g, '');
const [moduleName, imported] = path.split('/');

if (!locales[moduleName]) {
locales[moduleName] = {};
}
locales[moduleName][imported] = requireModule(fileName).default;
});

export default locales;

/*
{en: {…}, ko: {…}}
*/

Reference

Dependency Management Dynamic Loading