Skip to content

Instantly share code, notes, and snippets.

@Kinasha
Created January 30, 2023 03:43
Show Gist options
  • Save Kinasha/e357d9b3d48c8b2f259205908888804a to your computer and use it in GitHub Desktop.
Save Kinasha/e357d9b3d48c8b2f259205908888804a to your computer and use it in GitHub Desktop.
通过 webpack 的 require.context 将特定文件夹下的指定文件自定义导出
const req = require.context('./', true, /.jsx$/);
const filenames = req.keys();
const modules = filenames.map(req);
const components = {};
modules.forEach((mod, index) => {
const filename = filenames[index].slice(2, -4).replace(/\//g, '-');
// skin => IDCSkin
// skin-color => IDCSkinColor
const formatname = filename
.replace(/^\S/, s => s.toUpperCase()) // 首字母大写
.replace(/-(\w)/g, (s, w) => w.toUpperCase()); // 去短横线
const name = `IDC${formatname}`;
components[name] = mod.default;
});
export default components;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment