javascriptnode.jswebpackpixi.js

Can't import PIXI js as a module


I am trying to set a simple testing environment for PIXI js but the console debuger chokes at the import from PIXI

Uncaught TypeError: Failed to resolve module specifier "pixi.js". Relative references must start with either "/", "./", or "../".

Pixi.js has been installed with npm install pixi.js I am not experienced with webpack but it seems to be the problem.

index.html :

<!DOCTYPE html>
<html>
<head>
    <title>Pixel Animator</title>
    <meta charset="UTF-8" />
</head>
<body>
<script type="module" src="index.js"></script>
</body>
</html>

index.js :

import * as PIXI from "pixi.js"

... 

webpack.config.js :

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
    entry: './src/app.js',
    mode: 'development',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.js'
    },
    devServer: {
        contentBase: './dist'
    },
    plugins: [
        new CopyPlugin([
            { from: 'src/index.html', to: './' },
            { from: 'src/style.css', to: './' },
        ]),
    ],
};

Any idea what causes this to happen ?


Solution

  • If I understood your question correctly, this error occurs in the browser. Correct?

    If this is the case, the most likely culprit is that you are loading your index.js via index.html in browser directly. Browser naturally cannot locate pixi.js and fails. Yes, you might be loading index.html via webpack development server, but it just does not do anything useful at all for you.

    What is the reason for using webpack in the first place? My guess is: you want to bundle your entire app/game code into the single big JS file (app.js or game.js "bundle").

    If this is your intent, I suggest you do it step by step, making sure you test and understand each step in full details:

    When this works, create index.html and include the resulting "big bundle" of your game into it (just manually copying files as needed into the temporary folder). If all works fine, automate this step with webpack CopyPlugin or with HtmlWebpackPlugin.

    Finally, make sure this all works great with production minified build of the game, and with webpack development web server.