2

I want to dynamically import clusterApiUrl from "@solana/web3.js" using next/dynamic, but I get an error "clusterApiUrl is not a function".

This is how I import it:

const clusterApiUrl = dynamic(
  () => import("@solana/web3.js").then((mod) => mod.clusterApiUrl ),
  {
    ssr: false,
  }
);

and I use clusterApiUrl like this: const endpoint = useMemo(() => clusterApiUrl(network), [network]); I'm trying to reduce my bundle size

3
  • I'm not familiar with NextJS dynamic, but are you sure it can be used this way? The docs (nextjs.org/docs/advanced-features/dynamic-import) only show it being used for React components
    – Callum M
    Jan 20, 2023 at 15:16
  • yeah I later discovered it cant be used to import functions How do you suggest I reduce the import size of clusterApiUrl? Jan 20, 2023 at 17:51
  • I'm not sure that you can, Next should already be optimising the bundle to only import what's needed. If you use less of @solana/web3.js you should see a smaller bundle, with it getting larger as you import more. Can you update the question to include some bundle size numbers and exactly what code you're using?
    – Callum M
    Jan 23, 2023 at 10:17

2 Answers 2

1

You can use the same principle to import external libraries using import() at the point where that module is needed. Architect your code such that clusterApiUrl is only needed in a codepath that's inaccessible to the server renderer (eg. in an effect, or an event handler).

See ‘with external libraries’ in the Next.js ‘dynamic imports’ documentation.

1

this is the typescript signature of next.js dynamic

function dynamic<P = {}>(dynamicOptions: DynamicOptions<P> | Loader<P>, options?: DynamicOptions<P>)
                     // this is the return value
                     : React.ComponentType<P>

it should return a React component. You could try this

export const WrapperComponent = (props) => {
  // Make instance here 
  const clusterApi = useMemo(() => clusterApiUrl,[]);  

  // Do whatever you want here with the clusterApi

  return <div>Something</div>;
}

then dynamically import the WrapperComponent

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.