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
603 views
in Technique[技术] by (71.8m points)

next.js - Dynamic Importing of an unknown component - NextJs

I want to load a component dynamically based on the route. I'm trying to make a single page which can load any individual component for testing purposes.

However whenever I try to do import(path) it shows the loader but never actually loads. If I hard code the exact same string that path contains then it works fine. What gives? How can I get nextjs to actually dynamically import the dynamic import?

// pages/test/[...component].js

const Test = () => {
  const router = useRouter();
  const { component } = router.query;
  const path = `../../components/${component.join('/')}`;

  console.log(path === '../../components/common/CircularLoader'); // prints true

  // This fails to load, despite path being identical to hard coded import
  const DynamicComponent = dynamic(() => import(path), {
    ssr: false,
    loading: () => <p>Loading...</p>,
  });

  // This seems to work
  const DynamicExample = dynamic(() => import('../../components/Example'), {
    ssr: false,
    loading: () => <p>Loading...</p>,
  });

  return (
    <Fragment>
      <h1>Testing {path}</h1>
      <div id="dynamic-component">
        <DynamicComponent />      <!-- this always shows "Loading..." -->
        <DynamicExample /> <!-- this loads fine. -->
      </div>
    </Fragment>
  );
};

export default Test;
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I put dynamic outside of the component, and it work fine.

const getDynamicComponent = (c) => dynamic(() => import(`../components/${c}`), {
  ssr: false,
  loading: () => <p>Loading...</p>,
});

const Test = () => {
  const router = useRouter();
  const { component } = router.query;
  
  const DynamicComponent = getDynamicComponent(component);

  return <DynamicComponent />
}

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

...