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

Viewed 3181
3 Answers

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.

For Next.js 11, I had to slightly revise the answer from Emile:

Install the following package: yarn add next-transpile-modules

In your next.config.js file add the following:

const withTM = require('next-transpile-modules')(["package2", "package2"]);

module.exports = withTM({
  reactStrictMode: true
})

Put assets folder inside public folder. To access assets can be done by calling full path url.

await SceneLoader.Append(
  'http://localhost:3000/assets/characters/avatar.glb'
);

Related