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

如何让TypeScript项目导入特定npm模块时触发编译错误?求ESLint规则替代方案

实现TypeScript编译时限制特定导入的方案(替代ESLint no-restricted-imports)

如果你想在TypeScript编译阶段直接拦截特定包的特定模块导入,并抛出自定义错误,以下是几种无需依赖ESLint的方案:

方案1:利用TypeScript路径映射+类型声明文件

这是最简单的轻量方案,无需额外工具:

  1. 修改tsconfig.json的paths配置,把目标包指向自定义声明文件:
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@package/name": ["./src/restricted-imports.d.ts"]
    }
  }
}
  1. 创建src/restricted-imports.d.ts,对禁止的导出项声明为never类型并添加错误提示:
declare module '@package/name' {
  /**
   * ❌ 禁止从@package/name导入moduleName,请改用@other/package
   */
  export const moduleName: never;

  // 其他允许导出的模块可以正常声明(如果有)
  export const allowedModule: string;
}

当有人导入moduleName时,TypeScript会直接抛出编译错误,同时注释里的提示也能让开发者清楚替代方案。

方案2:自定义TypeScript语言服务插件

如果需要更灵活的规则(比如匹配多个模块、动态生成错误信息),可以写一个TS插件:

  1. 编写插件逻辑,监听导入语句并检查匹配规则:
import * as ts from 'typescript';

export function create(info: ts.server.PluginCreateInfo) {
  const originalService = info.languageService;
  const proxy = Object.create(originalService);

  // 重写语义诊断方法,添加自定义检查
  proxy.getSemanticDiagnostics = (fileName) => {
    const diagnostics = originalService.getSemanticDiagnostics(fileName);
    const sourceFile = originalService.getProgram()?.getSourceFile(fileName);
    if (!sourceFile) return diagnostics;

    // 遍历文件中的导入声明
    ts.forEachChild(sourceFile, (node) => {
      if (ts.isImportDeclaration(node)) {
        const importSource = node.moduleSpecifier.getText().replace(/['"]/g, '');
        if (importSource === '@package/name') {
          // 检查导入的命名绑定
          node.importClause?.namedBindings?.forEachChild((spec) => {
            if (ts.isImportSpecifier(spec) && spec.name.text === 'moduleName') {
              diagnostics.push({
                file: sourceFile,
                start: spec.getStart(),
                length: spec.getWidth(),
                messageText: "Please import 'moduleName' from '@other/package' instead.",
                category: ts.DiagnosticCategory.Error,
                code: 9999 // 自定义错误码
              });
            }
          });
        }
      }
    });

    return diagnostics;
  };

  return proxy;
}
  1. 在tsconfig.json中配置插件路径:
{
  "compilerOptions": {
    "plugins": [{ "name": "./src/custom-import-plugin.ts" }]
  }
}

这个方案完全融入TypeScript编译流程,错误会和原生TS错误一起显示。

方案3:使用第三方TypeScript工具库

如果不想自己写插件,可以用现成的ts-restrict-imports工具,它专门用于在编译阶段限制导入:

  1. 安装依赖后,在tsconfig.json中添加规则配置:
{
  "compilerOptions": {},
  "restrictImports": {
    "@package/name": {
      "deny": ["moduleName"],
      "message": "Please import 'moduleName' from '@other/package' instead."
    }
  }
}

运行TypeScript编译时,工具会自动检查并抛出对应的错误提示。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 16:42:31