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.
After a not so insignificant amount of time searching i finally learned the following.
@babylon (es6) is not compiled into javascript and is instead nicely defined (es6) typescript friendly library of source code. (helps when wanting to treeshake)
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With