根据错误信息,无法解析模块 'fs',这是因为在浏览器中无法直接访问文件系统(fs 模块是 Node.js 的内置模块之一,用于访问文件系统)。因此,在 Next.js 13 中,你不能在客户端代码中使用 fs 模块,只能在服务器端代码中使用。

如果你需要在 Next.js 应用程序中读取文件或数据,则应在服务器端使用 Node.js 模块来读取数据,并将其传递到客户端代码中。你可以在 Next.js 中使用 getStaticProps 或 getServerSideProps 函数来获取数据并将其传递给页面组件。

在获取数据后,你可以将数据传递给页面组件的 props,然后在组件中使用该数据。例如,在 /components/layout.tsx 组件中,你可以使用 props 参数来传递数据,然后在组件中使用该数据。

在 /lib/blog.ts 文件中,你可以使用 Node.js 模块来读取数据。你可以将数据读取到一个变量中,然后将其传递给页面组件。例如:

import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'

// 读取数据并返回一个数组
export function getBlogData() {
  const postsDirectory = path.join(process.cwd(), 'posts')
  const fileNames = fs.readdirSync(postsDirectory)

  return fileNames.map(fileName => {
    const id = fileName.replace(/\.md$/, '')

    const fullPath = path.join(postsDirectory, fileName)
    const fileContents = fs.readFileSync(fullPath, 'utf8')

    const matterResult = matter(fileContents)

    return {
      id,
      ...matterResult.data
    }
  })
}

然后,在页面组件中,你可以从 getStaticProps 或 getServerSideProps 函数中获取数据,并将其传递给组件。

import { getBlogData } from '@/lib/blog'

export async function getStaticProps() {
  const blogData = getBlogData()

  return {
    props: {
      blogData
    }
  }
}

function Layout({ children, blogData }) {
  // 使用 blogData 渲染页面
  return (
    <div>
      {children}
    </div>
  )
}

export default Layout
Nextjs 13 componentslayouttsx 怎么读取 libblogts 里的数据libSitets10Module not found Cant resolve fs 1 import fs from fs 2 import path from path 3 import matter from gray-matter 4 import Info from com

原文地址: https://www.cveoy.top/t/topic/bstU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录