如何使用 pixijs v5 配置我的 tsconfig?

How do I configure my tsconfig with pixijs v5?

我在我的打字稿项目中正确导入 PIXI js 时遇到了一个奇怪的问题。

问题是我在引用 PIXI 对象时从不需要使用 PIXI 前缀。

例如代替:

let s = new PIXI.Sprite(textureName);

我必须做的事情:

let s = new Sprite(textureName);

一切正常,只是有点烦人。我感觉这就是我的 tsconfig.json 文件的配置方式。

我如何配置它才能像第一个选项一样工作?

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "target":"es2015",
    "moduleResolution": "node"
  }
}

这是我的package.json

{
  "name": "tester",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "dependencies": {
    "gsap": "^2.1.3",
    "howler": "^2.1.1",
    "rxjs": "^6.4.0"
  },
  "devDependencies": {
    "@types/facebook-js-sdk": "^3.3.0",
    "@types/gsap": "^1.20.2",
    "@types/howler": "^2.0.5",
    "@types/pixi.js": "^4.8.7",
    "clean-webpack-plugin": "^1.0.1",
    "css-loader": "^2.1.0",
    "html-webpack-plugin": "^3.2.0",
    "npm-install-webpack-plugin": "^4.0.5",
    "pixi.js": "^5.0.3",
    "style-loader": "^0.23.1",
    "ts-loader": "^5.3.3",
    "typescript": "^3.2.4",
    "webpack": "^4.29.0",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^3.1.14"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --mode development",
    "build": "webpack --mode production"
  },
  "author": "",
  "license": "ISC"
}

这是一个示例 ts 文件。

import { Sprite, Texture } from "pixi.js";
import { IGameComponent } from "../interfaces/game-component.interface";

export class BaseSprite extends Sprite implements IGameComponent {
  constructor(texture?: Texture) {
    super(texture);
    this.interactive = false;
    this.interactiveChildren = false;
  }

  init(): void {
  }

  update(delta: number): void {
  }
}

你应该像这样导入 PixiJS:

import * as PIXI from "pixi.js";

这将从 pixi.js 导入所有元素并将它们放入 PIXI 命名空间。

您目前所做的只是导入一些元素并将它们直接放入 SpriteTexture 变量中:

import { Sprite, Texture } from "pixi.js";

ES 模块语法可能令人困惑,但它提供了很大的灵活性。您可以准确限制导入的内容。您还可以根据需要重命名任何模块或模块的一部分。 (当两个库使用相同的名称时很有用)。此参考列表 all the ways import 可以使用。


更新:

此外,一些插件假定 PIXI 在全局命名空间中存在。从版本 5 开始,不再有全局 PIXIv5 migration guide 解释了如何解决这个问题:

快速而肮脏的修复方法是将 PIXI 放入全局命名空间,如下所示:

import * as PIXI from 'pixi.js';
window.PIXI = PIXI; // some bundlers might prefer "global" instead of "window"

更好的解决方案是在 webpack 配置中填充 PIXI 全局变量。 (请参阅上面 link 的详细信息。)

对于 pixi.js v5,您应该将 "pixi.js" 模块添加到 compilerOptions 部分中的 tsconfig.json 类型。并删除 @types/pixi.js 模块。

tsconfig.json
{...
"compilerOptions": {
   ...,
   "types": ["pixi.js"],
   }
}

您可以使用 npm 包中的类型定义:

tsconfig.json
{...
"compilerOptions": {
   ...,
    "typeRoots" : ["node_modules/pixi.js"],
    "types" : ["pixi.js"],
   }
}

项目示例: https://github.com/andreytmk/pixijs5-ts-dev