Getting SyntaxError when using lightweight-charts in NextJS
Asked Answered
C

1

8

I'm trying to use the lightweight-charts package in my nextjs project, however when i try to call the createChart function I get this error in my nodejs console.

...\lightweight-charts\dist\lightweight-charts.esm.development.js:7
import { bindToDevicePixelRatio } from 'fancy-canvas/coordinate-space';
^^^^^^

SyntaxError: Cannot use import statement outside a module

Component:

import styled from "styled-components"
import { createChart } from 'lightweight-charts';

const Wrapper = styled.div``

const CoinPriceChart = () => {
  const chart = createChart(document.body, { width: 400, height: 300 });
  return <Wrapper></Wrapper>
}

export default CoinPriceChart

Page:

import styled from "styled-components"
import CoinPriceChart from "../../components/charts/CoinPriceChart"

const Wrapper = styled.div``

const CoinDetailPage = () => {
  return (
    <Wrapper>
      <CoinPriceChart />
    </Wrapper>
  )
}

export default CoinDetailPage

Does someone have an idea what I could do to enable me to use the library within nextjs? Thank you!

Councilwoman answered 12/4, 2021 at 13:18 Comment(1)
Does this help answer your question NextJS + react-hook-mousetrap : “Cannot use import statement outside a module”? Different lib but same solution.Tachycardia
D
9

That because you are trying to import the library in SSR context. Using next.js Dynamic with ssr : false should fix the issue :

import styled from "styled-components"
import dynamic from "next/dynamic";
const CoinPriceChart = dynamic(() => import("../../components/charts/CoinPriceChart"), {
  ssr: false
});

const Wrapper = styled.div``

const CoinDetailPage = () => {
  return (
    <Wrapper>
      <CoinPriceChart />
    </Wrapper>
  )
}

export default CoinDetailPage
Dodecasyllable answered 12/4, 2021 at 14:15 Comment(3)
This solved my problem, thank you very much Nico!Councilwoman
Nice is correct. I just wanna add a comment that if you need to import some others from "../../components/charts/CoinPriceChart" and they are not components, put them in a separate file. In my case, they are constants and typesMonophyletic
I get an error when doing suspense:true. Does someone has a solution for that?Enantiomorph

© 2022 - 2024 — McMap. All rights reserved.