Search code examples
javascriptecmascript-6browserify

How to import from excluded modules (ES6)?


I have a project for a browser app which I want to split in two parts. As a minimal example imagine that in ./core I have :

// core.js 
import SuperClass from "../core/SuperClass";    
export {SuperClass};

// SuperClass.js
class SuperClass
{
    constructor()
    {
        console.log('SuperClass constructor');
    }
}
export default SuperClass

and directory ./game has

//game.js   
import SuperClass from "../core/SuperClass";
console.log(SuperClass);

If I build with game.js as entry point everything is fine as all dependencies go into the bundle.

However, if I exclude the files from ./core (by using exclude function of browserify) and make a separate bundle with them and load before game.js with:

<script src="scripts/core.js"></script>
<script src="scripts/game.js"></script>

I get : Uncaught Error: Cannot find module '../core/SuperClass' from game.js

What is the way to provide those dependencies to game.js at runtime ? My build process uses gulp , babelify and browserify.


Solution

  • If you are adding the code via a <script> tag placed before your code, you can assume that is there, as a global variable/class/library, you don't need to import it because it is already present. It's like using the good old JQuery,for example: as you placed the file in your HTML file, you knew that $ was omnipresent