本文介绍了在 Next.js 中动态导入 abcjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的项目

import Music from '../components/music';
export default function Home() {
  return (
    <Music></Music>
  )
}
import dynamic from 'next/dynamic';
const abcjs = dynamic(import('abcjs'), { ssr: false });

export default function Music({note}) {
    return (
        <>
            <div id="paper"></div>
            {abcjs.renderAbc("paper", "X:1\nK:D\nDDAA|BBA2|\n")}
        </>
    )
}

我的 package.json

{
  "name": "music-quiz",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_OPTIONS='--inspect' next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "abcjs": "^5.12.0",
    "next": "10.2.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
  },
  "devDependencies": {
    "cross-env": "^7.0.3"
  }
}

但是,浏览器告诉我 abcjs.renderAbc 不是函数,据我所知这应该可以工作.

However, the browser tells me abcjs.renderAbc is not a function and as far as I can tell this should work.

如果它有任何区别,我将使用 npm run dev 运行 next.js.

If it makes any difference I'm running next.js with npm run dev.

如果我尝试记录 abcjs,我似乎得到了一个空对象.vscode 告诉我它找不到 abcjs 的声明类型,但这无关紧要.

If I try to log abcjs I appear to get sort of an empty object. vscode tells me that there is it cannot find a declaration type for abcjs, but that shouldn't matter.

显然库没有被正确导入,但我不知道为什么会这样.

Clearly the library isn't being imported correctly but I have no idea why this is.

我应该补充一点,我发现了这个 example 并将其调整为 next.

I should add that I found this example and are adapting it to next.

FAQ 关于这个,但它没有解决问题

There is also something in the FAQ about this, but it doesn't solve the issue

推荐答案

next/dynamic 用于动态导入 React 组件.

next/dynamic is used to dynamically import React components.

要动态导入常规 JavaScript 库,您只需使用 ES2020 dynamic import().

To dynamically import regular JavaScript libraries you can simply use ES2020 dynamic import().

import { useEffect } from "react";

export default function Music({ note }) {
    useEffect(() => {
        const abcjsInit = async () => {
            const abcjs = await import("abcjs");
            abcjs.renderAbc("paper", "X:1\nK:D\nDDAA|BBA2|\n")
        };
        abcjsInit();
    }, []);

    return (
        <div id="paper"></div>
    )
}

这篇关于在 Next.js 中动态导入 abcjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 11:43