javascriptanimationpixi.jsspine

Can't import plugin for lib


I try to import 'pixi-spine' plugin to my file where I imported PIXI lib. But I can't do it. I use webpack to package files. I try another variants to do it, but I have this error

import * as PIXI from 'pixi.js';
import {Spine} from 'pixi-spine';

import * as spineJSON1 from '../../../../../src/theme/assets/spine/ship_1_col_1.json';

export function newAnimations() {

  const app = new PIXI.Application();
  document.body.appendChild(app.view);

// load spine data
  app.loader
    .add('ship_1_col_1', spineJSON1)
    // .add('ship_1_col_1', 'src/theme/assets/spine/ship_1_col_1.json')
    .load(onAssetsLoaded);

  app.stage.interactive = true;
  app.stage.buttonMode  = true;

  function onAssetsLoaded(loader, res) {
    const ship_1_col_1 = new PIXI.spine.Spine(res.ship_1_col_1.spineData);

    // set current skin
    ship_1_col_1.skeleton.setSkinByName('ship_1_col_1');
    ship_1_col_1.skeleton.setSlotsToSetupPose();

    // set the position
    ship_1_col_1.x = 400;
    ship_1_col_1.y = 600;

    ship_1_col_1.scale.set(1.5);

    // play animation
    ship_1_col_1.state.setAnimation(0, 'idle', true);

    app.stage.addChild(ship_1_col_1);

    app.stage.on('pointertap', () => {
      // change current skin
      const currentSkinName = goblin.skeleton.skin.name;
      const newSkinName     = (currentSkinName === 'goblin' ? 'goblingirl' : 'goblin');
      ship_1_col_1.skeleton.setSkinByName(newSkinName);
      ship_1_col_1.skeleton.setSlotsToSetupPose();
    });
  }
}

But I have error from 'pixi-spine' - PIXI is not defined


Solution

  • Starting from version 5, PixiJS no longer provides PIXI in the global namespace.

    From the v5 migration guide:

    [With] Webpack and 3rd-party plugins, like pixi-spine, you might have difficulties building the global PIXI object resulting in a runtime error ReferenceError: PIXI is not defined. Usually this can be resolved by using Webpack shimming globals.

    For instance, here's your import code:

    import * as PIXI from 'pixi.js';
    import 'pixi-spine'; // or other plugins that need global 'PIXI' to be defined first
    

    Add a plugins section to your webpack.config.js to let know Webpack that the global PIXI variable make reference to pixi.js module. For instance:

    const webpack = require('webpack');
    
    module.exports = {
        entry: '...',
        output: {
            ...
        },
        plugins: [
         new webpack.ProvidePlugin({
           PIXI: 'pixi.js'
         }) ] }