Import matter-js in typescript project

纵饮孤独 提交于 2019-12-10 09:35:36

问题


I found this file :

https://www.npmjs.com/package/@types/matter-js

i execute this line :

npm install --save @types/matter-js

In root ts file i got error message :

'Matter' refers to a UMD global, but the current file is a module. Consider adding an import instead.

Code looks like :

///<reference path="matter-js.d.ts"/>

import Ioc from "./libs/ioc";
let master = new Ioc();
console.log(master);
console.log(Matter);

Error in browser:

app.ts:11 Uncaught ReferenceError: Matter is not defined

Did i need to load matter-js.js lib ?

If i put :

import matter from 'matter-js'

i get :

Module ''matter-js'' has no default export.


回答1:


You can try to load it using import * as matter from 'matter-js', that should work.




回答2:


I load the matter.js library with a script tag. Did you forget that?

<script src="js/matter.min.js"></script>

And I installed the typings with

npm install @types/matter-js



回答3:


Unfortunately, the typescript lib seems outdated. Last commit 2 years ago. Parameters that should be optional are instead required in the typescript definitions...




回答4:


You can also do

var Matter = require('matter-js');

or

import { Engine, World, Body, Bodies, Constraint } from 'matter-js';

The @types/matter-js is missing the Common class, but maybe you shouldn't use that anyway. If you really need it, you can add this to the index.d.ts in the package,

export class Common {
    static extend(obj:any, deep?:boolean): any;
    static clone(obj:any, deep?:boolean): any;
    static keys(obj:any): any;
    static values(obj:any): any;
    static get(obj:any, path:string, begin:number, end:number): any;
    static set(obj:any, path:string, val:any, begin:number, end:number): any;
    static shuffle(array:any[]): any;
    static choose(choices:any[]): any;
    static isElement(obj:any):boolean;
    static isArray(obj:any):boolean;
    static isFunction(obj:any):boolean;
    static isPlainObject(obj:any):boolean;
    static isString(obj:any):boolean;
    static clamp(value:number, min:number, max:number):number;
    static sign(value:number): number;   
    static now(): number;
    static random(min?:number, max?:number): number;
    static colorToNumber(colorString:string): number;
    static log(...objs:any[]): void;
    static info(...objs:any[]): void;
    static warn(...objs:any[]): void;
}


来源:https://stackoverflow.com/questions/49734671/import-matter-js-in-typescript-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!