5

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

Emile
  • 11,451
  • 5
  • 50
  • 63

3 Answers3

13

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.

Philippe
  • 861
  • 10
  • 10
Emile
  • 11,451
  • 5
  • 50
  • 63
  • 1
    I had to use `@babylonjs/core` for it to work ie, `const withTM = require("next-transpile-modules")(["@babylonjs/core"]);` – zlog Feb 09 '21 at 22:50
  • weirdly, i had to update my code this this as well. – Emile Feb 16 '21 at 16:51
  • This helped, thanks for going through the trouble. I did notice a huge difference in build time though. I'll probably have to read on tree shaking because all I have is the canvas (literally) and it's showing red on my build file size (while also taking very long). – tcaissie May 06 '21 at 19:40
4

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
})
LudacrisX1
  • 330
  • 1
  • 5
  • 12
-1

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'
);