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!

  • Does this help answer your question [NextJS + react-hook-mousetrap : “Cannot use import statement outside a module”](https://stackoverflow.com/a/66246141/1870780)? Different lib but same solution. – juliomalves Apr 12 '21 at 20:41

1 Answers1

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
Nico
  • 6,259
  • 4
  • 24
  • 40
  • 1
    This solved my problem, thank you very much Nico! – marcell-janovszki Apr 13 '21 at 12:34
  • 1
    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 types – hungdoansy Jan 02 '22 at 07:42
  • I get an error when doing suspense:true. Does someone has a solution for that? – Allleex Dec 02 '22 at 10:45