next.jsbabylonjs

@Babylonjs (ES6) in Nextjs failes with unexpected token 'export'


I'm building my website with Nextjs and importing Bablyonjs was throwing up the following error.

syntaxError: Unexpected token 'export'
module.exports = require("@babylonjs/core")

I'm using the standard nextjs setup with tsconfig.json I'm refering to this Babylon documentation and using the examples verbatim.

enter image description here


Solution

  • After a not so insignificant amount of time searching i finally learned the following.

    1. @babylon (es6) is not compiled into javascript and is instead nicely defined (es6) typescript friendly library of source code. (helps when wanting to treeshake)

    2. Nextjs out of the box isn't configured to compile anything in node_modules. It expects precompiled javascript ready to consume.

    Point 2. is why i received the error, nextjs was expecting compiled js and it was getting uncompiled source.

    To fix this you need to add a next.config.js and configure it with next-transpile-modules and next-compose-plugins.

    yarn add next-transpile-modules
    yarn add next-compose-plugins
    

    next.config.js

    //const withTM = require('next-transpile-modules')(['@babylonjs']);
    const withTM = require('next-transpile-modules')(['@babylonjs/core']); // As per comment.
    const withPlugins = require('next-compose-plugins');
    
    const nextConfig = {
        target: 'serverless',
        webpack: function (config) {
            /// below is not required for the problem described. Just for reference.(es6)
            config.module.rules.push({test: /\.yml$/, use: 'raw-loader'})
            return config
        }
    }
    
    module.exports = withPlugins([withTM], nextConfig);
    

    It compiled without error after this.

    References Handy links i came across solving this issue.

    Links that helped some on the way to understanding the problem.