Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

reactjs - Dynamically import abcjs in Next.js

I have a simple project

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
K:D
DDAA|BBA2|
")}
        </>
    )
}

my package.json is

{
  "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"
  }
}

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

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

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

next/dynamic is used to dynamically import React components.

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
K:D
DDAA|BBA2|
")
        };
        abcjsInit();
    }, []);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...