Next.js Discord

Discord Forum

How to dynamically import with dynamic path all files from directory

Unanswered
Cape May Warbler posted this in #help-forum
Open in Discord
Cape May WarblerOP
Is it possible to dynamically import all files from some directory specified in config.json?
I'm trying to build an NPM package that would help with building dynamic pages using block components, right now I have to import all blocks manually, then make a switch and return respective block, I would like to automate this process by dynamically importing all components from directory specified in config.json and omit writing this switch.
Right now I'm getting error "Cannot find module" where path is correct but I believe it's problem with bundler that might be impossible to get thru

1 Reply

Wuchang bream
When I made an NPM package, I originally used a file path as well. This worked for express, but not NextJS since the paths change when building. I ended up creating an overall class and configured the package to tell it what I wanted. You can decide if this works for your use as well.

NPM Package - Index.js:
class PackageClass {
   constructor (config) {
      this.path = config.path
   }
}


and this when being used as a dependency:
const { PackageClass } = require('npm-package')

const npmPack = new PackageClass({
    path: 'path'
})