如何批量导入多JS文件并按条件调用对应变量
批量导入结构化JS文件的优化方案
问题背景
现有如下目录结构的JS文件:
lib ├─ a │ ├─ file_a_01.js │ ├─ file_a_02.js │ ├─ file_a_03.js ├─ b │ ├─ file_b_01.js │ ├─ file_b_02.js ├─ c │ ├─ file_c_01.js ├─ d ├─ file_d_01.js ├─ file_d_02.js ├─ file_d_03.js ├─ file_d_04.js
每个文件仅导出一个与文件名同名的变量,例如:
// file_a_01.js export let file_a_01 = [1,2,3,4,5]
手动逐个导入并按条件调用的方式,会因文件数量增多变得难以维护;尝试用循环批量导入时,又存在不知道文件夹文件数量、字符串拼接的文件名无法直接转为变量使用的问题。
解决方案
方案1:使用动态导入(Dynamic Import)
利用ES动态导入特性,根据条件拼接路径按需加载文件,无需提前知晓文件数量:
async function getTargetData(condition, num) { const lowerCondition = condition.toLowerCase(); const paddedNum = num.toString().padStart(2, '0'); // 补零匹配文件名格式 try { // 拼接路径并动态导入模块 const module = await import(`/lib/${lowerCondition}/file_${lowerCondition}_${paddedNum}.js`); // 通过字符串键名获取导出的变量 return module[`file_${lowerCondition}_${paddedNum}`]; } catch (err) { console.error('目标文件不存在:', err); return null; } } // 使用示例 async function useData() { const someCondition = "A"; const otherCondition = 1; const targetData = await getTargetData(someCondition, otherCondition); if (targetData) { // 在这里使用目标数据 console.log(targetData); } }
方案2:创建统一入口文件
在各子目录和根目录创建入口文件,批量导出模块,后续通过对象属性直接访问:
- 子目录入口(以
lib/a/index.js为例):
// 手动导出(适合文件数量少的场景) export { file_a_01 } from './file_a_01.js'; export { file_a_02 } from './file_a_02.js'; export { file_a_03 } from './file_a_03.js'; // 构建工具自动批量导出(Vite/Webpack支持) const modules = import.meta.glob('./file_a_*.js', { eager: true }); for (const path in modules) { const moduleName = path.match(/file_a_\d+/)[0]; exports[moduleName] = modules[path][moduleName]; }
- 根目录入口(
lib/index.js):
export * as a from './a/index.js'; export * as b from './b/index.js'; export * as c from './c/index.js'; export * as d from './d/index.js';
- 调用示例:
import * as lib from '/lib/index.js'; function useData(someCondition, otherCondition) { const lowerCondition = someCondition.toLowerCase(); const targetName = `file_${lowerCondition}_${otherCondition.toString().padStart(2, '0')}`; const targetData = lib[lowerCondition][targetName]; if (targetData) { console.log(targetData); } else { console.error('目标数据不存在'); } } useData("A", 1);
方案3:利用构建工具的批量导入能力
如果使用Vite、Webpack等构建工具,可直接用其API自动扫描目录下的所有目标文件:
以Vite为例:
// 批量导入lib下所有符合规则的文件 const modules = import.meta.glob('/lib/**/file_*.js', { eager: true }); // 构建数据映射表,键为`condition_num`格式 const dataMap = {}; for (const path in modules) { const match = path.match(/lib\/(\w+)\/file_(\w+)_(\d+)\.js/); if (match) { const condition = match[1].toUpperCase(); const num = parseInt(match[3]); const key = `${condition}_${num}`; const varName = `file_${match[2]}_${match[3]}`; dataMap[key] = modules[path][varName]; } } // 使用时直接通过键获取数据 function useData(someCondition, otherCondition) { const key = `${someCondition}_${otherCondition}`; const targetData = dataMap[key]; if (targetData) { console.log(targetData); } }
内容的提问来源于stack exchange,提问作者louislugas
相关产品推荐
相关产品推荐

