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

如何在Webpack+PNPM+TypeScript+React项目中正确使用MetaMask SDK?

解决@metamask/sdk无类型提示及TS7016警告问题

1. 先确认SDK版本

部分旧版@metamask/sdk未内置TypeScript类型声明,先升级到最新稳定版:

pnpm add @metamask/sdk@latest

2. 检查tsconfig.json配置

确保你的TypeScript配置正确开启类型检测,关键配置项如下:

{
  "compilerOptions": {
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": false, // 不要跳过库类型检查,确保能识别内置声明
    "moduleResolution": "NodeNext"
  }
}

3. 手动补全类型声明(如果升级后仍无效)

如果SDK目录里确实没有.d.ts文件,在项目根目录新建types/metamask-sdk.d.ts文件,添加基础类型声明(可根据你用到的功能补充):

declare module '@metamask/sdk' {
  export class MetaMaskSDK {
    constructor(options?: {
      dappMetadata?: {
        name: string;
        url: string;
      };
    });

    connect(): Promise<{ accounts: string[]; chainId: string }>;
    getProvider(): any; // 若需要更精确类型,可参考官方文档补充
    // 其他用到的方法都可以在这里添加类型定义
  }
}

接着在tsconfig.json里配置typeRoots,让TS识别自定义类型:

{
  "compilerOptions": {
    "typeRoots": ["./types", "./node_modules/@types"]
  }
}

4. 正常导入使用

完成以上配置后,按照官方方式导入就能获得类型提示,示例代码:

import { MetaMaskSDK } from '@metamask/sdk';

const mmSdk = new MetaMaskSDK({
  dappMetadata: {
    name: '你的DApp名称',
    url: window.location.host,
  },
});

const ethereumProvider = mmSdk.getProvider();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:10:03