markdown - 使用 Next.js 时,如何将我的博客的静态资产与我的 markdown 文件一起保存,而不是放在公共文件夹下?
问题描述
我正在用 Next.js 创建一个博客。
https://dev.to/imranib/build-a-next-js-markdown-blog-5777或https://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 文件的相对路径来引用图像。
是否有捷径可寻?我在想我需要在构建过程中将所有资产复制content
到public
以使这项工作正常进行。
更新 1:我正在使用我正在使用next-mdx-remote,它不允许在 mdx 文件中导入。
解决方案
我认为可以使用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
},
}
}
参考
请注意,答案主要是我基于官方示例的最有根据的猜测。我希望它有所帮助或提供一些有用的信息。
推荐阅读
- python - tf.constant_initializer 值是否存储在图形中,就像常量如何存储在 tensorflow 中一样?如果不是,常量值存储在哪里?
- java - 在 Tomcat 服务器上部署 JAR 和执行 java -jar 之间的区别
- ruby-on-rails - 如何绕过错误 ActiveRecord::RecordNotFound?
- java - 如何使用 Java 语言在 Hack Reactor 中创建 100kx100k 矩阵?
- r - nnfor 库如何选择 elm 和 mlp 网络中每一层的节点数?
- c# - Aspnetboilerplate:无法将日志写入 SQL Server
- django - 如何在 Django 中向 Waffle App 添加额外的验证?
- php - 数组到 MySQL PHP
- talend - 有没有办法让所有匹配从 tmap 到列表
- php - 从条件的关系中获取最后一个