Error encountered during Svelte/Vite/Pixi.js build: Unable to utilize import statement outside of a module

I'm currently diving into a project that involves Svelte-Kit (my first venture into svelte), Vite, TypeScript, and Pixi. Whenever I attempt to execute vite build, the dreaded error

Cannot use import statement outside a module
rears its ugly head. Despite having
"type": "module"
specified in my package.json and feeling confident about the rest of my setup, importing from both pixi.js/dist/esm/pixi.js and pixi.js/dist/cjs/pixi.js results in more error messages. I seem to be missing a crucial step here, so any guidance would be warmly welcomed!

It's worth noting that I've opted for pnpm for managing my packages.

(node:42972) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
{path}/node_modules/.pnpm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="20504958490e4a5360160e140e12">[email protected]</a>/node_modules/pixi.js/dist/esm/pixi.js:8
import '@pixi/polyfill';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
[SyntaxError: Cannot use import statement outside a module]
 ELIFECYCLE  Command failed with exit code 1.

My suspicion is that there might be something amiss in my vite.config.js file:

// vite.config.js

import { sveltekit } from '@sveltejs/kit/vite';
import adapter from '@sveltejs/adapter-netlify';

/** @type {import('vite').UserConfig} */
const config = {
    plugins: [sveltekit()],
    kit: {
        adapter: adapter({ split: true })
    },

    optimizeDeps: {
        exclude: ['@apollo/client', 'svelte-apollo'],
        include: ['pixi.js']
    },
    ssr: {
        noExternal: ['@apollo/client', 'svelte-apollo']
    }
};

export default config;

In this project, I have a component named Canvas.svelte that is imported into the index.svelte file. Inside the Canvas.svelte, I bring in Pixi like this:

// Canvas.svelte

<script lang="ts" type="module">
    ...other imports
    import * as PIXI from 'pixi.js';
    ...rest of file
</script>
package.json

...rest of file,
"devDependencies": {
        "@apollo/client": "^3.6.8",
        "@contentful/rich-text-types": "^15.12.1",
        "@sveltejs/adapter-netlify": "1.0.0-next.70",
        "@sveltejs/kit": "next",
        "@types/cookie": "^0.5.1",
        "@types/gsap": "^3.0.0",
        "@types/tinycolor2": "^1.4.3",
        "@typescript-eslint/eslint-plugin": "^5.27.0",
        "@typescript-eslint/parser": "^5.27.0",
        "apollo": "^2.34.0",
        "cookie": "^0.4.1",
        "graphql": "14.0.0",
        "prettier": "^2.6.2",
        "prettier-plugin-svelte": "^2.7.0",
        "sass": "^1.53.0",
        "svelte": "^3.49.0",
        "svelte-apollo": "^0.5.0",
        "svelte-check": "^2.8.0",
        "svelte-preprocess": "^4.10.7",
        "tslib": "^2.4.0",
        "typescript": "^4.7.4",
        "vite": "^3.0.2"
    },
    "type": "module",
    "dependencies": {
        "@fontsource/poppins": "^4.5.8",
        "@pixi/filter-kawase-blur": "^4.1.5",
        "@pixi/polyfill": "^6.4.2",
        "gsap": "^3.10.4",
        "pixi.js": "^6.4.2",
        "svelte-pixi": "^0.1.3",
        "svelte2tsx": "^0.5.11",
        "tinycolor2": "^1.4.2"
    }

Answer №1

After some investigation, I discovered that the build process is pulling from the esm directory by default. To fix this issue, I included the following configuration in my vite.config.js:

resolve: {
  alias: {
    'pixi.js': path.resolve(__dirname, './node_modules/pixi.js/dist/browser/pixi.mjs')
  }
},

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

Preserving type information in TypeScript function return values

Wondering how to make this code work in TypeScript. Function tempA copies the value of x.a to x.temp and returns it, while function tempB does the same with x.b. However, when calling tempA, the compiler seems to forget about the existence of the b field ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

The 'ngModel' property cannot be bound to a 'textarea' element because it is not recognized as a valid property

When I run Karma with Jasmine tests, I encounter the following error message: The issue is that 'ngModel' cannot be bound since it is not recognized as a property of 'textarea'. Even though I have imported FormsModule into my app.modu ...

Exploring the method for obtaining parameters from a generic constructor

I have a customized class called Collection, which takes another class as a parameter named personClass. I expect the method add to accept parameters that are used in the constructor of the class User class Person { constructor(public data: object) { } ...

The Angular Material Table is not showing any data on the screen

My challenge is to consolidate data from 4 different endpoints in order to generate a ListElement that will populate an angular material table. Despite receiving the correct data in my logs, the table remains empty. Interestingly, when I include a conditio ...

Is there a way to modify a single object within an array?

Here is the HTML representation of my data: https://i.sstatic.net/VbKQ4.png page.html <ul id="elements"> <li *ngFor="let elem of fetchdata" (click)="log(elem)"> {{elem.title}} {{elem.description}} </li> ...

Build a stopwatch that malfunctions and goes haywire

I am currently using a stopwatch that functions well, but I have encountered an issue with the timer. After 60 seconds, I need the timer to reset to zero seconds and advance to one minute. Similarly, for every 60 seconds that pass, the minutes should chang ...

What is the process for creating a unit test case for an Angular service page?

How can I create test cases for the service page using Jasmine? I attempted to write unit tests for the following function. service.page.ts get(): Observable<Array<modelsample>> { const endpoint = "URL" ; return ...

Using TypeScript, effortlessly retrieve objects within React components based on their keys

I am looking for a way to dynamically choose a React component based on a key within an object import React, {useState, useEffect} from 'react' import ComponentA from '@components/ComponentA'; import ComponentB from '@components/Co ...

A guide on implementing radio buttons in Angular 2 and sending the selected value via a HTTP post request

As a newcomer to Angular 2, I am struggling with the following code: Here is my HTML <form action="POST" (submit)="register()" class="aa-login-form"> <input type="radio" [(ngModel)]="gender" name="sex" value="MALE"> Male <input ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

PrimeNG's p-table in Angular is not being recognized when using @ViewChild

Here is the code snippet I am referring to: import { DataTable } from 'primeng/primeng'; @Component({ moduleId: module.id, templateUrl: 'search.component.html' }) export class SearchComponent { @ViewChild(DataTable) pr ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

The function 'ShouldWorkController' was expected but is not defined, receiving undefined instead

Whenever I attempt to connect a controller to a template using the angular-ui-router $stateProvider, I encounter this error message: 'ShouldWorkController' is not a function. Got undefined. Surprisingly, when I define the controller within the ...

Error encountered while reading JSON data using Angular4 and TypeScript: Json

When a user selects one or more checkboxes and submits a form, data in the database is updated. At that moment, I call location.reload() from the code to reload the page and display the correct data. Below is the backend web API code: [HttpGet] public as ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

Developing custom events in an NPM package

Developing a basic npm package with signalr integration has been my recent project. Here's how it works: First, the user installs the package Then, the package establishes a connection using signalr At a certain point, the server triggers a function ...

Dealing with a multi-part Response body in Angular

When working with Angular, I encountered an issue where the application was not handling multipart response bodies correctly. It seems that the HttpClient in Angular is unable to parse multipart response bodies accurately, as discussed in this GitHub issue ...