reactjs 如何使用Next.js与Nexttra库在mdx文件中嵌入youtube视频?

qv7cva1a  于 2023-03-08  发布在  React
关注(0)|答案(1)|浏览(171)

我正在用这个Portfolio Starter Kit来写我的旅游博客,唯一缺少的功能是把youtube视频嵌入到博客文章中,这样它们就可以在现场播放,而不必在www.example.com上youtube.com打开新的页面。
我使用了ChatGPT-s的帮助,但是由于我是Next.js和Nextra的新手,我无法发现ChatGPT-s的错误并进行调试。
1.在你的项目中安装react-youtube软件包:

yarn add react-youtube

1.创建自定义MDX组件以呈现YouTube视频:在项目目录中创建一个名为YouTube.js的新文件。在该文件中,定义一个新组件,该组件使用react-youtube库中的YouTube组件来呈现YouTube视频。以下是该文件的示例:

import YouTube from 'react-youtube';

const YouTubeComponent = ({ videoId }) => {
  const opts = {
    height: '360',
    width: '640',
    playerVars: {
      // https://developers.google.com/youtube/player_parameters
      autoplay: 0,
    },
  };

  return <YouTube videoId={videoId} opts={opts} />;
};

export default YouTubeComponent;```

1.在Next.js配置中注册自定义MDX组件:在Next.js配置文件(通常为next.config.js)中,可以通过添加以下代码将YouTubeComponent注册为自定义MDX组件:

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [],
    rehypePlugins: [],
    // Register custom components here
    // Here, we're registering a component called 'youtube' that uses our custom YouTubeComponent
    components: {
      youtube: './components/YouTube',
    },
  },
});

module.exports = withMDX();

1.在降价内容中使用自定义组件:在Markdown内容中,您现在可以使用“youtube”标签嵌入YouTube视频。以下是一个示例,显示了它可能的外观:

Here is a YouTube video:

<youtube videoId="dQw4w9WgXcQ" />

添加所有这些并运行yarn run build后,我得到这个错误:

Failed to compile.

./pages/ajaveeb/2023-02-18-youtube-embedding.mdx
TypeError [ERR_INVALID_ARG_TYPE]: The "from" argument must be of type string. Received undefined
    at new NodeError (node:internal/errors:400:5)
    at validateString (node:internal/validators:163:11)
    at Object.relative (node:path:1191:5)
    at loader (file:///Users/kristjan.roosild/repos/what-does-this-button-do/node_modules/nextra/dist/loader.mjs:85:42)

以下是变更https://github.com/kristjanr/what-does-this-button-do/pull/1/files的PR

vvppvyoh

vvppvyoh1#

对于 typescript ,请使用此导入YouTube,{ YouTubeProps }来自“react-youtube”;

相关问题