NextJS在MDX中导入图像

时间:2018-06-07 16:46:12

标签: javascript reactjs nextjs

我尝试了一个官方的NextJS MDX-Blog示例。 https://github.com/mdx-js/mdx/tree/master/examples/next

但我无法弄清楚的是如何设置NextJS配置以通过webpack加载图像?

import img from "./image.jpg"

## Hallo Blogwelt

![My own Image]({img})

4 个答案:

答案 0 :(得分:1)

将您的npm install --save-dev less-loader@3.0.0 想象成要添加到幕后现有"schematics": { "@schematics/angular:component": { "styleext": "less" } }, 上的东西。您将无法直接访问该Webpack,但可以对其进行扩展。

因此,要加载图像,您需要一个合适的图像加载器。

我发现next-images最容易使用:

next.config.js

然后您可以导入:

webpack.config

答案 1 :(得分:1)

您还可以使用/public目录保存图像。例如,如果您在/public/image.jpg上添加图片,则可以在博客文章中引用该图片,如下所示:

![Alt Text](/image.jpg)

答案 2 :(得分:0)

嘿,谢谢你的提示!

自6月以来已经有一段时间了,今天又尝试了一次,现在它的工作像我期望的那样。

  1. 我拿了MDX/Next Example

  2. 像这样编辑next.config.js:

    const withPlugins = require('next-compose-plugins');
    const images = require('remark-images');
    const emoji = require('remark-emoji');
    const optimizedImages = require('next-optimized-images');
    
    const withMDX = require('@zeit/next-mdx')({
      extension: /\.mdx?$/,
      options: {
        mdPlugins: [images, emoji]
      }
    });
    
    module.exports = withPlugins([
     [
       withMDX,
       {
         pageExtensions: ['js', 'jsx', 'md', 'mdx']
       }
     ],
       [optimizedImages]
     ]);
    

现在,它的工作原理与预期的完全一样,在页面文件夹中的Markdown文件中,我可以执行以下操作:

import Layout from '../../components/Layout'
import Image from './catimage.jpg'


# Hey guys this is the heading of my post!

<img src={Image} alt="Image of a cat" />

答案 3 :(得分:0)

对不起,我迟到了,但使用 Next v11,您可以直接导入图像。

话虽如此,您可以为 Webpack 添加自定义加载器来修改您的 mdx 文件并使用自定义组件来处理图像。例如:

// save this somewhere such as mdxLoader and
// add it to your webpack configuration
const replaceAll = require("string.prototype.replaceall");

module.exports = function (content, map, meta) {
  return replaceAll(
    map
    content,
    /\!\[(.*)\]\((.+)\)/g,
    `<NextImage alt="$1" src={require('$2').default} />`
  );
};

并处理它:

// and reference this in your MDX provider
const components = {
  NextImage: (props: any) => {
    return <Image alt={props.alt || "Image"} {...props} />;
  },
};

现在您可以在帖子中使用 Markdown 风格的图片了!

![my image](./image.png)

但是,包括 ./ 相对前缀。