javascript - 在 NextJS 中使用轻量级图表时出现 SyntaxError

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

我正在尝试使用 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 中使用该库吗?
谢谢!

最佳答案

那是因为您试图在 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

关于javascript - 在 NextJS 中使用轻量级图表时出现 SyntaxError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67059133/

相关文章:

javascript - 由于上下文切换,函数可能永远不会被调用吗?

node.js - Passport jwt 验证回调未调用

azure - 如何将 Azure 应用程序见解与 nextjs 应用程序结合使用

reactjs - 如何在 Next.js 中使用自定义主题配置 Ant Design 并支持 CSS 模块功能

javascript - 获取给定元素和类的特定元素

javascript - 使用 knockout.js 时最好的 IDE 是什么?

javascript - For循环在传递给函数之前递增到限制

authentication - 未在生产中使用 express-session 设置 Cookie

javascript - 在滚动时将类添加到 <li> 元素内的链接

node.js - 共享模块的 NestJS 问题