My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Splitting Phaser CE with Webpack?

Jos Faber's photo
Jos Faber
·Oct 27, 2017

I'm using Phaser CE with Webpack, but the bundle gets huge (3.4Mb!). It's probably not built to use modular. Is there a way to split it?

// main.js

"use strict";

import 'pixi'
import 'p2'
import Phaser from 'phaser'

import BootState from './states/Boot'
import SplashState from './states/Splash'
import GameState from './states/Game'

import config from './config'

class Game extends Phaser.Game {
  constructor () {
    super(config.gameWidth, config.gameHeight, Phaser.AUTO, 'phaser_stage', null)

    this.state.add('Boot', BootState, false)
    this.state.add('Splash', SplashState, false)
    this.state.add('Game', GameState, false)

    this.state.start('Boot')
  }
}

window.game = new Game()
// webpack.config.js

var path = require("path");
var webpack = require('webpack');

// Phaser webpack config
var phaserModule = path.join(__dirname, '/node_modules/phaser-ce/')
var phaser = path.join(phaserModule, 'build/custom/phaser-split.js')
var pixi = path.join(phaserModule, 'build/custom/pixi.js')
var p2 = path.join(phaserModule, 'build/custom/p2.js')

module.exports = {

    entry: {
      "main": "./app/main.js",
      "challenge1": "./app/challenge1/main.js"
    },

    output: {
        path: path.join(__dirname, "web/js"),
        filename: '[name].bundle.js',
        chunkFilename: '[id].chunk.js'
    },

    plugins: [
      new webpack.optimize.CommonsChunkPlugin({
        name: "vendor",
        minChunks: Infinity,
      })
    ],

    module: {
        rules: [
          { test: /pixi\.js/, use: ['expose-loader?PIXI'] },
          { test: /phaser-split\.js$/, use: ['expose-loader?Phaser'] },
          { test: /p2\.js/, use: ['expose-loader?p2'] }
        ]
    },

    node: {
      fs: 'empty',
      net: 'empty',
      tls: 'empty'
    },

    resolve: {
      alias: {
        'phaser': phaser,
        'pixi': pixi,
        'p2': p2
      }
    },

    watch: true
};
// webpack output

               Asset       Size  Chunks                    Chunk Names
challenge1.bundle.js    3.37 MB       0  [emitted]  [big]  challenge1
      main.bundle.js  391 bytes       2  [emitted]         main
    vendor.bundle.js    5.78 kB       3  [emitted]         vendor
   [1] (webpack)/buildin/global.js 509 bytes {0} [built]
   [2] ./app/challenge1/config.js 3.82 kB {0} [built]
   [3] ./app/main.js 285 bytes {2} [built]
   [4] ./app/challenge1/main.js 556 bytes {0} [built]
  [11] ./app/challenge1/states/Boot.js 323 bytes {0} [built]
  [12] ./app/challenge1/states/Splash.js 1.91 kB {0} [built]
  [13] ./app/challenge1/states/Game.js 5.38 kB {0} [built]
  [14] ./app/common/numberutils.js 588 bytes {0} [built]