5

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\nK:D\nDDAA|BBA2|\n")}
        </>
    )
}

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

2
  • 1
    next/dynamic is used to dynamically import React components, which abcjs is not. Commented May 6, 2021 at 9:30
  • @juliomalves do you know how to import non-react client side libraries? Commented May 6, 2021 at 10:11

1 Answer 1

7

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\nK:D\nDDAA|BBA2|\n")
        };
        abcjsInit();
    }, []);

    return (
        <div id="paper"></div>
    )
}
Sign up to request clarification or add additional context in comments.

2 Comments

Does this actually create a separate chunk file?
@NevinMadhukarK Yes, this will create a separate chunk for abcjs, that will be loaded separately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.