首页 > 解决方案 > 使用 Next.js 时,如何将我的博客的静态资产与我的 markdown 文件一起保存,而不是放在公共文件夹下?

问题描述

我正在用 Next.js 创建一个博客。

https://dev.to/imranib/build-a-next-js-markdown-blog-5777https://dev.to/tinacms/creating-a-markdown-blog-with-next-js-52hk谈话关于如何拥有一个内容/博客文件夹来保存降价文件。

理想情况下,我希望将每个帖子的资产保存在它自己的文件夹中。

根据Next.js 文档

Next.js 可以在根目录中名为 public 的文件夹下提供静态文件,如图像。然后,您的代码可以从基本 URL (/) 开始引用公共内部的文件。

但是,我不想将降价文件放在一个地方,而将它的图像放在另一个地方。我想要一个这样的文件夹结构:

- pages
  - [blog].js
- content
  - posts
    - my_first_post
      - index.mdx
      - assets
         - banner.jpeg
         - another_image.png
    - my_second_post
      - index.mdx
      - assets
         - banner.jpeg

在每个 .mdx 文件中,它仍会通过其与 .mdx 文件的相对路径来引用图像。

是否有捷径可寻?我在想我需要在构建过程中将所有资产复制contentpublic以使这项工作正常进行。

更新 1:我正在使用我正在使用next-mdx-remote,它不允许在 mdx 文件中导入。

标签: markdownnext.jsblogsstatic-site

解决方案


我认为可以使用next-image插件来完成。

您可以像这样添加插件

const withImages = require('next-images')
module.exports = withImages({
  webpack(config, options) {
    return config
  }
})

如果你使用withPlugins包,你可以尝试如下

module.exports = withPlugins(
  [
    [
      withImages,
      {
        inlineImageLimit: 10240,
      },
    ],
    [withCSS]
  ]
);

配置插件后,您应该可以像下面这样导入图像

import BannerImg from "./assets/image.jpeg"

在我个人看来,public如果您想使用 CDN,我认为使用该文件夹会非常有用。您可以简单地配置assetPrefix以根据您的环境为您的资产添加CDN 路径。

更新 1:使用next-mdx-remote

我做了一些搜索。Next.js 存储库中有一个关于如何使用该包的示例。对于您的具体问题。我认为这可能有效,

// import you component. you can proabably import image directly 
import CustomImgTag from 'CustomImgTag';

// Custom components/renderers to pass to MDX.
// Since the MDX files aren't loaded by webpack, they have no knowledge of how
// to handle import statements. Instead, you must include components in scope
// here.
const components = {
  img: CustomImgTag,
  // It also works with dynamically-imported components, which is especially
  // useful for conditionally loading components for certain routes.
  // See the notes in README.md for more details.
  TestComponent: dynamic(() => import('../../components/TestComponent')),
  Head,
}


// You can pass the the config to renderToString
export const getStaticProps = async ({ params }) => {
  // ...... other code

  const mdxSource = await renderToString(content, {
    components,
    // ...... additional config
  })

  return {
    props: {
      source: mdxSource
    },
  }
}

参考

请注意,答案主要是我基于官方示例的最有根据的猜测。我希望它有所帮助或提供一些有用的信息。


推荐阅读