【问题标题】:Getting SyntaxError when using lightweight-charts in NextJS在 NextJS 中使用轻量级图表时出现 SyntaxError
【发布时间】:2021-07-07 13:53:06
【问题描述】:

我正在尝试在我的 nextjs 项目中使用 lightweight-charts 包,但是当我尝试调用 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 中使用该库吗? 谢谢!

【问题讨论】:

标签: javascript node.js next.js lightweight-charts


【解决方案1】:

那是因为您尝试在 SSR 上下文中导入库。 使用 next.js Dynamicssr : 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

【讨论】:

  • 这解决了我的问题,非常感谢 Nico!
  • Nice 是正确的。我只想添加一条评论,如果您需要从“../../components/charts/CoinPriceChart”导入其他一些并且它们不是组件,请将它们放在单独的文件中。就我而言,它们是常量和类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2021-11-15
相关资源
最近更新 更多