alienzhou / web-highlighter

✨ A no-runtime dependency lib for text highlighting & persistence on any website ✨🖍️
https://alienzhou.github.io/web-highlighter/
MIT License
888 stars 144 forks source link

在Next.js项目中使用报错 "window is not defined" #109

Closed tianxiuali closed 1 year ago

tianxiuali commented 1 year ago

在Next.js项目中import Highlighter from 'web-highlighter'就会报错

Snipaste_2023-06-12_10-24-46

tao commented 1 year ago

You can import the library dynamically on NextJS.

import { useEffect } from 'react'
import Highlighter from "web-highlighter"

const Highlight = () => {
  useEffect(() => {
    let highlighter = new Highlighter()

    highlighter.run()

    return () => highlighter.dispose()
  }, [])

  return (
    <></>
  )
}

export default Highlight
import Navbar from './navbar'
import Footer from './footer'

import dynamic from 'next/dynamic'
const Highlight = dynamic(() => import('./Highlight'), { ssr: false })

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
          <main>{children}</main>
          <Highlight />
      <Footer />
    </>
  )
}
tianxiuali commented 1 year ago

You can import the library dynamically on NextJS.

import { useEffect } from 'react'
import Highlighter from "web-highlighter"

const Highlight = () => {
  useEffect(() => {
    let highlighter = new Highlighter()

    highlighter.run()

    return () => highlighter.dispose()
  }, [])

  return (
    <></>
  )
}

export default Highlight
import Navbar from './navbar'
import Footer from './footer'

import dynamic from 'next/dynamic'
const Highlight = dynamic(() => import('./Highlight'), { ssr: false })

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
          <main>{children}</main>
          <Highlight />
      <Footer />
    </>
  )
}

Oh cooool! It works! Thank you so much!