Anonymous function bundle where the imported namespace is undefined

Here is the code snippet I am working with:

import * as Phaser from 'phaser';

new Phaser.Game({
    width:300,
    height:300,
    scale: {
        mode: Phaser.Scale.FIT,
    },
    type: Phaser.AUTO,
    scene: { create() {} },
});

Upon compiling and running this code, I encountered an error in the bundle:

Uncaught ReferenceError: Phaser is not defined

rollup.config.js

import typescript from '@rollup/plugin-typescript';

export default {
  input: 'src/EntryPoint.ts',
  output: {
    file: 'dist/EntryPoint.js',
    format: 'iife',
  },
  plugins: [
    typescript(),
  ],
};

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <script src="./dist/EntryPoint.js"></script>
</body>
</html>

package.json

{
  "name": "rollup-import-issue-mvc",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "build": "rollup -c",
    "start": "rollup -c && sirv --dev --max-age 0 --port 3000",
    "watch": "rollup -c -w",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@rollup/plugin-typescript": "^8.3.2",
    "phaser": "3.55.2",
    "rollup": "^2.72.1",
    "sirv-cli": "^2.0.2",
    "typescript": "^4.6.4"
  }
}

MVC: https://github.com/Klaider/rollupjs-issue-0

Below is a section of the bundle causing the issue:

(function (Phaser) {
    'use strict';

    // ...

})(Phaser); // line where I get ReferenceError

UPDATE

Further investigation revealed the following warning:

(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
phaser (imported by src/EntryPoint.ts)
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
phaser (guessing 'Phaser')

It's worth noting that phaser is listed as a dependency in NPM.

Answer №1

You can discover the solution in the link provided along with this warning:

Warning: "Treating [module] as external dependency"

Rollup will only handle relative module IDs by default. For instance, an import statement like this…

import moment from 'moment';

…will not lead to moment being included in your bundle – instead, it will be a necessary external dependency at runtime. If that's the desired behavior, you can eliminate this warning using the external option, making your intentions clear:

// rollup.config.js  
export default {  
 entry: 'src/index.js',  
 dest: 'bundle.js',  
 format: 'cjs',  
 external: ['moment'] // <-- suppresses the warning  
};

If you wish to include the module in your bundle, you must instruct Rollup on how to locate it. This typically involves utilizing @rollup/plugin-node-resolve.

Certain modules like events or util are inherent to Node.js. Including them (for example, for browser compatibility) may require adding rollup-plugin-polyfill-node.

In your scenario, it is essential to employ @rollup/plugin-node-resolve:

import typescript from '@rollup/plugin-typescript';
import { nodeResolve } from '@rollup/plugin-node-resolve';

export default {
  input: 'src/EntryPoint.ts',
  output: {
    file: 'dist/EntryPoint.js',
    format: 'iife',
  },
  plugins: [
    typescript(),
    nodeResolve()
  ],
};

Note: You might also need to utilize @rollup/plugin-commonjs as mentioned here

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

"Choose one specific type in Typescript, there are no in-b

Need help returning an object as a fetch response with either the property "data" or "mes": { data: Data } | { mes: ErrMessage } Having trouble with TypeScript complaining about this object, let's call it props: if (prop.mes) return // Property &a ...

Looking for a solution to the error message: "X is not able to be assigned to the type 'IntrinsicAttributes & Props'"

Greetings everyone! I need some assistance in setting up single sign-on authentication using React, Azure AD, and TypeScript. I'm encountering a type error in my render file and I'm unsure of how to resolve it. Below is the specific error message ...

Discover the process of implementing nested service calls in Angular 2 by utilizing observables

Here are my component file and service file. I am trying to achieve that after the verification() service method is successfully called, I want to trigger another service method signup() within its success callback inside subscribe. However, I am encounter ...

Differences between Typescript compilation: Using dot notation vs square brackets when accessing non-existent properties

Imagine having the given class and code snippet: class myClass{ x: number; } const obj = new myClass(); obj.y = 7; // produces a compile error. Property 'y' does not exist on type myClass. obj['y'] = 7; // compiles without any issu ...

Tips for adjusting card content to fit its size in material ui?

I'm looking to implement Material UI cards in a grid layout, each containing a Highcharts chart as shown in this demo. However, I'm facing an issue where the content does not adjust properly when the card size is fixed. How can I resolve this? A ...

The addition of special characters to strings in TypeScript through JavaScript is not functioning as expected

I need assistance on conditionally appending a string based on values from captured DOM elements. When the value is empty, I want to include the special character "¬". However, when I try adding it, I get instead because the special character is not reco ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

What is the most suitable data type to represent an empty object?

When I declared the return type of the function below as {}, eslint flagged an error stating not to use {} as a type because it actually means "any non-nullish value". After understanding the meaning behind this error, I realize that specifying return typ ...

Exploring Click Events in Angular with OpenLayers Features

After creating a map with parking points as features, I now want to implement a click function for the features. When a feature is clicked, I want to display a popup with the corresponding parking data. I've tried searching online for information on ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

Tips for showcasing JSON data in an HTML table or list

I am seeking a way to dynamically display changing JSON object data in a table using Angular. The structure of the JSON object is subject to change due to server updates. JSON Object: { "This item has 1 value":1, "Another":30, "It ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...

Is it feasible to mock a defined function in Typescript for a unit test scenario?

Currently, I am working on typescript code that compiles into javascript, gets bundled with rollup, and is utilized by a framework. This framework exposes a library to me in the global scope, taking the form of a function: fun({ prop1: number, ...

Does nestjs support typescript version 3.x?

Currently embarking on a new project using Nestjs. I noticed in one of its sample projects, the version of Typescript being used is 2.8. However, the latest version of Typescript is now 3.2. Can anyone confirm if Nest.js supports version 3.x of Typescrip ...

Connecting to Multiple Databases in NestJS with MySQL Without Defining Entities

If you're interested in learning about connecting to MySQL using TypeORM and defining Entities, the NestJS documentation has all the information you need. In a situation where you have to connect to a MySQL server with multiple databases and need to ...

Issue TS2365: The operation of addition cannot be performed between an array of numbers and the value -1000

I'm encountering an error in my ng serve logs despite the function functioning properly with no issues. However, I am concerned as this may pose a problem when building for production. How can I resolve this error? uuidv4() { return ([1e7]+-1e3+- ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

Issue a tslint warning when mockResolvedValueOnce is used with async/await

While working with the request-promise module, everything seems to be functioning correctly except for a warning from tslint. Below is my unit test: import * as request from 'request-promise'; jest.mock('request-promise', () => { ...

Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing ...