Webpack 4, how to import a module into another module that are both entry points?

Viewed 1112

I'm new to Webpack, so my terms may not be entirely correct. What I'm trying to do is build a custom Phaser module first, then import it into the other entry point, which depends on it.

EDIT: I've tried using SplitChunks, Dynamic Imports, and aliases. But no avail. Is there anyway to accomplish this via plugins or methodology?

From webpack.config.js:

entry: {
       'phaser.min': './phaser-builder.js',
       game: './src/index.js'

   },

   resolve: {
       alias: {
           'eventemitter3': path.resolve(__dirname, './node_modules/eventemitter3')
       },
       modules: [ 'node_modules/phaser/src', 'node_modules' ]
   },

   output: {
       path: path.resolve(__dirname, 'build'),
       filename: '[name].js',
       library: 'Phaser',
       libraryTarget: 'umd',
       sourceMapFilename: '[file].map',
       devtoolModuleFilenameTemplate: 'webpack:///[resource-path]',
       devtoolFallbackModuleFilenameTemplate: 'webpack:///[resource-path]?[hash]',
       umdNamedDefine: true
   },

Contents of phaser-builder.js:

require('polyfills');

var CONST = require('const');
var Extend = require('utils/object/Extend');

var Phaser = {

   ... code ...
};

Phaser = Extend(false, Phaser, CONST);
module.exports = Phaser;
global.Phaser = Phaser;

index.js (second entry point) needs the 'Phaser' object from phaser.min.js that is created from ./phaser-builder.js (first entry point) as shown below:

Contents of index.js:

//import 'phaser';  //this works but it's not the custom build from entry point one.
import { Phaser } from '../build/phaser.min';
import { TestScene } from './scenes/TestScene';

const gameConfig = {
  width: 680,
  height: 400,
  scene: TestScene
};

new Phaser.Game(gameConfig);

Contents of TestScene.js: (imported in index.js)

export class TestScene extends Phaser.Scene {
    preload() {
    this.load.image('logo', 'assets/sprites/logo.png');
    }

    create() {
        this.add.text(100, 100, 'Working...', { fill: '#0f0' });
        this.add.image(100, 200, 'logo');
    }
}

As commented in index.js above, if I simply use import 'phaser'; (which is pulling from node_modules I presume?) Everything works fine. But that is the full phaser lib, which I don't want. I want to import the custom build I created in entry point one, that exists in /build/phaser.min.js

If I try importing from /build/phaser.min.js I get this error:

"TypeError: Super expression must either be null or a function"

Which from my understanding is basically saying that Phaser object/module is undefined, so TestScene is not extending Phaser.Scene as expected.

1 Answers

With webpack I add specific build of phaser in the followed way, I hope this is what you are looking for or at least will give you any idea how could we do with webpack

phaser build file

entry point for the phaser chunk

thank you.

Related