Developing a library for Phaser.io using WebPack - Error message: Class extending an undefined value is neither a constructor nor null

I am currently working on developing a compact FOSS UI component library specifically for the Phaser.io game engine. The code repository can be found here. All the components are stored in the src/ directory and are exported through the index.js file. These components are bundled using webpack.config.js and then exported to build/phaser-ui.js.

The challenge I am facing involves utilizing the compiled file. Within the test/ folder, I have set up a Phaser Game for testing with the help of the phaser-plus Yeoman generator. The package phaser-ui is included in the test's package.json using a relative link, which seems to be functioning correctly.

The underlying issue revolves around my phaser-ui file not having access to the Phaser Library. In the test game, I am attempting to import a component from the phaser-ui package.json dependency, resulting in an error being thrown.

Code snippet inside the Game.js state:

import ProgressBar from "phaser-ui";

https://i.sstatic.net/5dPDb.png https://i.sstatic.net/6DCGo.png

For further discussion, check out this post on the HTML5 Game Dev Forums here. The source repository can also be accessed here.

Answer №1

Within your code, starting from line 1:

/*
 * Star
 * ====
 *
 * Individual star particles in the background star emitters
 */

export default class Star extends Phaser.Particle {
// ...

It appears that you have forgotten to import the necessary library. The error states that Phaser is undefined, thus resulting in Phaser.Particle being undefined as well.

Could it be possible that you neglected to include

const Phaser = require('phaser');
before utilizing Phaser?

Alternatively, you can utilize modern syntax by doing

import {default as Phaser} from 'phaser';
if you prefer this method and have already configured your environment accordingly.

Answer №2

After some trial and error, I managed to get my project working perfectly. I made adjustments to my test script so that the package is properly reinstalled in the test directory each time:

In the package.json file for PHASER-UI:

"scripts": {
 "test": "npm run build && cd test && npm install phaser-ui && npm start",
 "build": "webpack"
},

The test package installs phaser-ui from a local NPM directory.

In the package.json file for TEST:

"dependencies": {
    "phaser-ce": "^2.7.0",
    "phaser-ui": "file:../"
  },

I also included the 'Phaser' variable as an external in my webpack configuration:

var webpack = require('webpack');

module.exports = {
    entry: './src/index.js',
    output: {
        path: 'build/',
        filename: 'phaser-ui.js'
    },
    externals: {
        Phaser: 'Phaser'
    }
};

Although the build was successful and everything seemed to be functioning, I encountered an issue when trying to use it in my game state. Importing and logging it only displayed a generic object in the console:

import * as lib from 'phaser-ui';

export default class Game extends Phaser.State {

  create() {
    console.log(lib)
  }

}

Update

I discovered that I needed to make some changes to my webpack.config.js file. By default, webpack libraries are meant to be used via a global variable, but I wanted mine to be consumed as a node module. To achieve this, I changed the libraryTarget to umd:

Updated webpack.config.js:

module.exports = {
    entry: './src/index.js',
    output: {
        path: 'build/',
        filename: 'phaser-ui.js',
        libraryTarget: 'umd', 
        library: 'phaserUi'
    },        
    externals: {
        Phaser: 'Phaser'
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

tickPositions becomes undefined upon introducing a second Y-Axis

I encountered an issue with my Highcharts chart when using the addSeries method along with two Y-axes. As this project employs Backbone, I have simplified the code in a JSFiddle that can be accessed here: http://jsfiddle.net/michalcarson/V84pP/. The code ...

Learn how to create a fading effect for an element when the mouse is inactive, and have it fade back in when the mouse is active again using J

There is a div with the ID "#top" that I want to have fade out after 3 seconds of mouse inactivity. Once the mouse is moved again, I would like it to fade back in. Any suggestions on how to achieve this effect? Appreciate your help! ...

Please enter data into the input fields provided in the text

Below is the code where Google transliteration is used for typing in Indian language in a text field. There are two routes with different page IDs. Initially, the transliteration works fine on the default page. However, when changing routes, an error occur ...

What steps can be taken to prevent the controller action if the password and confirm password do not match?

Currently utilizing .Netcore MVC for my project. I am developing a registration page where users are required to input their email, password, and confirm the password. Although I can verify if the entered password matches the confirmation password, the con ...

Validating ReactJS properties

Transitioning from ReactJs to React-Native, I came across this function structure in a react-native button code by Facebook: class Button extends React.Component<{ title: string, onPress: () => any, color?: ?string, hasTVPreferredFocus?: ?bo ...

Invoking PHP function through Ajax

I'm having trouble with a PHP function not running when using AJAX. Although the AJAX post request is working correctly, here's the code snippet: function thumbs(i) { $('.thumbs-up' + String(i)).click(function(){ $(this).a ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...

Executing an automated process of adding items to the shopping cart using Python without the need to have a

Does anyone know of a way to automate the add-to-cart process using Python without the need for an open browser window? I've experimented with modules like mechanize, but they lack the ability to directly interact with web elements. Currently, I&apo ...

Achieve maximum height with background images

Having trouble with responsiveness on my box containing a background image. I am aiming for the box to adjust its height based on the background image, as I have set the background-size attribute to auto. html: <div class="index_boxs" id="discover_win ...

How can you handle undefined values in the query object parameter when using Mongoose's Find function?

Alright: Sound.find({ what: req.query.what, where: req.query.where, date: req.query.date, hour: req.query.hour}, function(err, varToStoreResult, count) { //perform some actions }); Let's consider a scenario where only req.query.what has a ...

Error 431 is encountered when submitting an Axios post request

Facing a 431 (Request Header Fields Too Large) error when trying to submit a form in my single-page project through an axios request. I've attempted setting maxContentLength and maxBodyLength to Infinity, as well as adding max-http-header-size in the ...

Creating a single header that can be used across multiple pages in HTML

Hello there, I've been on the hunt for a JavaScript code that will allow me to create one header for multiple HTML pages. Unfortunately, my search has come up empty-handed. Can anyone offer some advice on how to achieve this? Thank you! ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

Can you please guide me on determining the type of the root element using jQuery?

I have an ajax request that can return either an error code or a user ID <?xml version="1.0" encoding="UTF-8"?> <error>1000</error> <?xml version="1.0" encoding="UTF-8"?> <userID>8</userID> Is there a way to determine ...

Developing a new object in Angular from an API call

Utilizing Angular 8, my goal is to retrieve data from the test JSON API located at https://jsonplaceholder.typicode.com/users and convert it into an array of User objects with the following structure: export interface User { name: string; email: str ...

How Can You Update the State of a Parent Component from a Child Component?

My Objective In the initial component, I retrieve items with a status of 2 and display them as checkboxes. In the subsequent component, I update the status of these items to 3. In the third component, a modal opens after the status change from the secon ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

What is the best way to extract the text from a class only when it is nested within a particular header tag?

const request = require ('request'); const cheerio = require('cheerio'); const fs = require ('fs'); request("http://kathmandupost.ekantipur.com/news/2018-08-31/bimstec-summit-multilateral-meet-underway.html", (error, response ...

How can I make rows appear dynamically when the user clicks a button?

I am trying to add rows dynamically when the user clicks on a button. I have created a script for this purpose, but unfortunately, it is not working as expected. Can someone please assist me with fixing it? <script> var i; i = 2; function AddR ...