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

TypeScript项目引入matter-js遇类型定义及全局引用错误求助

Fixing the 'Matter' UMD Global/Module Conflict in TypeScript

Alright, let's break down why you're seeing these errors and fix them step by step:

First, understand the root cause

Your file includes an import statement (import Ioc from "./libs/ioc"), which tells TypeScript to treat this file as an ES module. In module mode, TypeScript isolates the global scope—so even though you added the triple-slash reference to the type definitions, you can't directly access the UMD global Matter variable. Plus, the browser error happens because you never actually imported the matter-js library code itself (you only installed the type definitions, not the core library).

Step 1: Install the core matter-js library (if you haven't already)

You installed @types/matter-js for type support, but that's just the type definitions—you need the actual library too. Run this command:

npm install --save matter-js

Step 2: Replace the triple-slash reference with a proper ES module import

Instead of relying on the global Matter variable, import it directly into your module. You have two options:

Option 1: Import the entire Matter object (most straightforward)

import Matter from 'matter-js';
import Ioc from "./libs/ioc";

let master = new Ioc();
console.log(master);
console.log(Matter); // Now this works without errors

Option 2: Import only the parts you need (for smaller bundle sizes)

If you don't need the entire Matter library, you can import specific modules:

import { Engine, World, Bodies } from 'matter-js';
import Ioc from "./libs/ioc";

let master = new Ioc();
console.log(master);
console.log(Engine); // Access individual modules directly

Why this works

  • By using import, you're properly pulling the matter-js code into your module, which fixes the browser's ReferenceError (the library is now loaded and scoped to your module).
  • TypeScript will automatically use the @types/matter-js definitions with this import, so you still get full type checking and autocomplete.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:17:01