4

我正在尝试lightweight-charts在我的项目中使用该包nextjs,但是当我尝试调用该createChart函数时,我在 nodejs 控制台中收到此错误。

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

SyntaxError: Cannot use import statement outside a module

零件:

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

页:

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

const Wrapper = styled.div``

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

export default CoinDetailPage

有人知道我可以做些什么来使我能够在 nextjs 中使用该库吗? 谢谢!

4

1 回答 1

4

那是因为您试图在 SSR 上下文中导入库。Dynamic使用next.jsssr : false应该可以解决问题:

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
于 2021-04-12T14:15:28.287 回答