Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AmCharts in NextJS - SyntaxError: Unexpected token 'export'

When attempting to use '@amcharts/amcharts4/core' package and other amchart modules within a NextJS project I was getting an error:

SyntaxError: Unexpected token 'export'

After reading lots of posts and info about it I found this issue very helpful which allowed me to find the solution which is dynamic imports, I will share the solution below of how I solved it.

https://github.com/amcharts/amcharts4/issues/272

like image 205
thomallen Avatar asked Oct 23 '25 10:10

thomallen


1 Answers

The solution to this issue for me was to use NextJS dynamic imports so you isolate the amcharts code within a component and then import the component dynamically ONLY on the client side, not during SSR.

// Create a psuedo component using dynamic import that will only be imported client-side
const Chart = dynamic(() => import('./ChartComponent'), {
  ssr: false
})

./ChartComponent should have all your amcharts imports in it, which are now isolated and will only be imported in the client and should work just fine.

Then render the component like usual

return <Chart chartData={chartData} />

Docs for dynamic imports here: https://nextjs.org/docs/advanced-features/dynamic-import

like image 151
thomallen Avatar answered Oct 25 '25 00:10

thomallen