You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为CommonJS模块xmllint定义TypeScript类型时遇导入异常

解决TypeScript中xmllint导入后为空/undefined的问题

核心问题

你的问题出在两个关键点:类型定义文件未被TypeScript正确加载,以及类型定义未匹配xmllint的实际CommonJS导出结构,导致编译通过但运行时无法正确获取模块导出内容。

修复步骤

1. 确保类型定义文件被TypeScript识别

你的index.d.ts放在根目录,但tsconfig.json的include仅包含src目录,TypeScript可能无法加载该类型文件。可二选一调整:

  • 将index.d.ts移动到src目录下;
  • 修改tsconfig.json的include字段,添加根目录的类型文件:
{
  "include": [
    "src",
    "index.d.ts"
  ]
}

2. 修正类型定义以匹配xmllint的导出结构

xmllint是CommonJS模块,实际通过exports.validateXML挂载命名导出,你需要调整类型定义适配该结构:

declare module 'xmllint' {
    export interface ValidationResult {
        errors: string[];
    }

    export interface Options {
        xml: string;
        xsd: string;
    }

    export const validateXML: (opts: Options) => ValidationResult;
}

若上述写法仍有问题,可改用CommonJS专属的export =语法:

declare module 'xmllint' {
    export interface ValidationResult {
        errors: string[];
    }

    export interface Options {
        xml: string;
        xsd: string;
    }

    function validateXML(opts: Options): ValidationResult;

    export = validateXML;
}

3. 调整导入方式适配类型定义

  • 若使用命名导出的类型定义,用ES模块方式导入:
import { validateXML } from 'xmllint';

// 使用示例
const result = validateXML({ xml: '<test/>', xsd: '<xs:schema.../>' });
  • 若使用export =的类型定义,用CommonJS风格导入:
import xmllint = require('xmllint');

// 使用示例
const result = xmllint({ xml: '<test/>', xsd: '<xs:schema.../>' });

4. 验证基础依赖正确性

确认已正确安装xmllint包:

npm install xmllint --save

如果是浏览器环境,确保打包工具(如Webpack、Vite)已配置处理CommonJS模块,避免导出内容被错误解析。

替代方案

无需自行编写类型定义,可尝试安装社区维护的类型包:

npm install @types/xmllint --save-dev

安装后直接导入即可,TypeScript会自动识别类型。

内容的提问来源于stack exchange,提问作者Arthur Attout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 23:51:12