TypeScript项目引入matter-js遇类型定义及全局引用错误求助
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 thematter-jscode into your module, which fixes the browser'sReferenceError(the library is now loaded and scoped to your module). - TypeScript will automatically use the
@types/matter-jsdefinitions with this import, so you still get full type checking and autocomplete.
内容的提问来源于stack exchange,提问作者Nikola Lukic

