Node.js TypeScript中使用mysql-import模块报错求助
解决mysql-import在TypeScript中的两个常见错误
错误1:Importer构造与导入异常
问题分析
默认导入Importer后无法作为构造函数使用,或提示“仅作为类型使用”,是因为mysql-import的模块导出方式在TypeScript中需要适配,部分场景下类型定义未正确映射构造函数。
解决步骤
- 优先安装官方类型依赖(若存在):
npm install @types/mysql-import --save-dev
- 调整导入语句,若ES模块默认导入不生效,改用CommonJS风格导入:
// 替代原import语句 const Importer = require('mysql-import').default;
同时确保tsconfig.json的module字段设置为CommonJS或ESNext,保证模块解析逻辑正确。
错误2:progress参数类型缺失
问题分析
TypeScript无法自动推断onProgress回调中progress的类型,需手动定义或导入已有类型。
解决步骤
- 若有官方类型定义,直接导入对应类型:
import Importer, { ImportProgress } from 'mysql-import';
- 若无官方类型,手动声明类型接口:
interface ImportProgress { bytes_processed: number; total_bytes: number; }
- 在回调中明确指定参数类型:
imp.onProgress((progress: ImportProgress) => { const percent = Math.floor(progress.bytes_processed / progress.total_bytes * 10000) / 100; console.log(`${percent}% Completed`); });
修正后的完整代码
import Importer from 'mysql-import'; // 手动声明进度参数类型(若无官方类型时使用) interface ImportProgress { bytes_processed: number; total_bytes: number; } export async function ImportData(dbNew: string[]) { await CleanDatabase(dbNew); // 简化async/await写法,移除冗余的Promise.resolve.then const imp = new Importer({ host: dbNew[0], user: dbNew[1], password: dbNew[2], database: dbNew[3] }); try { imp.onProgress((progress: ImportProgress) => { const percent = Math.floor(progress.bytes_processed / progress.total_bytes * 10000) / 100; console.log(`${percent}% Completed`); }); await imp.import('./zelanard_c_sheet.sql'); const filesImported = imp.getImported(); console.log(`${filesImported.length} SQL file(s) imported.`); } catch (error) { console.error(error); return error; } }
内容的提问来源于stack exchange,提问作者Jonas Alexander Offersen
相关产品推荐
相关产品推荐

