Search code examples
reactjsnext.jsabcjs

How to dynamically import non-React client side libraries 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\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


Solution

  • 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>
        )
    }