
本文介绍一种基于动态导入(dynamic import)的轻量级方案,使 deno 应用能根据命令行参数(如 deno run main.ts config1)实时加载对应配置模块,避免静态导入限制,同时保障代码模块化与可维护性。
本文介绍一种基于动态导入(dynamic import)的轻量级方案,使 deno 应用能根据命令行参数(如 deno run main.ts config1)实时加载对应配置模块,避免静态导入限制,同时保障代码模块化与可维护性。
在 Deno 中,静态 import 语句在编译期解析,无法根据运行时参数(如 Deno.args[0])动态切换模块——这导致直接使用 import { data } from ./${configName}.ts`会报语法错误。而动态import()` 是 promise-based 的运行时机制,支持字符串路径拼接,是实现“按需加载配置”的标准解法。
以下是一个完整、可立即运行的模块化实现:
目录结构:
project/ ├── main.ts ├── process.ts ├── config1.ts ├── config2.ts └── config3.ts
*config1.ts(及其他 config.ts):**
export const data = "Config1";
process.ts(核心逻辑封装):
/** * 根据配置名动态加载对应模块,并生成处理结果 * @param configName 配置文件名(不含 .ts 后缀) * @returns 处理后的字符串结果 */ export async function calculate(configName: string): Promise<string> { try { const modulePath = `./${configName}.ts`; const configModule = await import(modulePath); if (typeof configModule.data !== "string") { throw new Error(`Config module "${configName}" must export a string 'data'`); } return `${configModule.data} is used.`; } catch (err) { if (err instanceof TypeError && err.message.includes("not found")) { throw new Error(`Configuration file "${configName}.ts" not found. Available: config1.ts, config2.ts, config3.ts`); } throw err; } }
main.ts(入口,接收 CLI 参数):
import { calculate } from "./process.ts"; // 获取第一个命令行参数(如 deno run main.ts config2) const configArg = Deno.args[0]; if (!configArg) { console.error("❌ Error: Please specify a config name, e.g., `deno run main.ts config1`"); Deno.exit(1); } // 执行动态加载与计算,并输出结果 calculate(configArg) .then(console.log) .catch((err) => { console.error("❌", err.message); Deno.exit(1); });
✅ 运行示例:
deno run main.ts config1 # 输出:Config1 is used. deno run main.ts config2 # 输出:Config2 is used. deno run main.ts missing # 输出错误:Configuration file "missing.ts" not found...
⚠️ 关键注意事项:
- 路径安全:import() 路径必须为相对或绝对 URL;禁止用户输入任意路径(如 ../etc/passwd),生产环境应校验 configName 是否匹配白名单正则(例如 /^config[1-9]d*$/);
- 类型安全:typescript 无法静态推断动态导入模块的类型,建议配合 JSDoc 注释或 satisfies(TS 4.9+)增强可读性;
- Deno 权限:首次运行需添加 –allow-read 权限(deno run –allow-read main.ts config1),因动态导入需读取文件系统;
- 缓存行为:Deno 对同一路径的 import() 结果自动缓存,多次调用相同配置不会重复加载,性能有保障。
该方案将“配置选择”与“业务逻辑”彻底解耦:process.ts 封装通用加载与转换流程,main.ts 专注 CLI 协作,各 config*.ts 仅负责声明数据——真正实现了高内聚、低耦合的模块化设计。