1

In my next.js + express.js (custom server within next) app, there is a flow of follows:

  1. user selects a parameter with drop down menu.
  2. upon her/his selection of parameter, a process is executed in the backend. 2.1. upon the parameter, I define the a filePath, like filePath = "myPath/parameter/coords.js"
  3. when the process is finished, it creates a file and writes some coordinates info.
  4. when the process is finished I "require(file)" and will be showing the coordinates on my leaflet comp.

Therefore I need something like this

if (processIsFinished) {
   const coords = require(filePath)

}

My questions are:

  1. I cannot define filePath with a variable. When I say /Users/..../parameter/coords.js, it is ok, no error (if there is already a file, which refers to my question-2) but since parameter is selected by user, I want the filePath defined as a var. I tried:

    const coords = require(filePath)

    const coords = require(${filePath})

    const coords = require(myPath/${parameter}/coords)

    const coords = require('' + filePath)

all did not work... how can we define the path in require with a variable?

  1. when there is no file, the "require" throws error, even if it is put in a conditional statement block (if statement). how can we make it work, like, if the "processIsFinished" then execute the require statement, because then there will be such a file.

Thanks...

m-alptekin
  • 11
  • 5
  • Why not Nextjs Dynamic Imports? https://nextjs.org/docs/advanced-features/dynamic-import – MC Naveen Apr 24 '23 at 07:54
  • I already used it dynamic() with my leaflet component (with no SSR option). Map is already loaded. But to be frank I was just searching this idea, like, dynamically load ANOTHER map instance when "processIsFinished"... I will try to do this, as I am also new to next. thanks. – m-alptekin Apr 24 '23 at 07:59
  • next dynamic() import did not work when requiring "not existing file"... whatever the case require needs a file, empty or not... – m-alptekin Apr 24 '23 at 10:04

1 Answers1

0

imports cannot be made with dynamic path names, this includes the require function.

but there is a workaround for this problem here. Results may vary as its non conformant.

Cpreet
  • 148
  • 1
  • 8