Is there any way in JS to import dynamically some modules ?
For example, this is my architecture :
| - index.js
| - modules
| - SomeModule
| - router.js
| - controller.js
| - SomeOtherModule
| - SubModule
| - router.js
| - controller.js
| - controller.js
My goal is to import all the router.js
modules in the index.js
file so I was thinking about something like this :
import fs from "fs"
import path from "path"
function scanDirForRouters (dirPath, name = "") {
let routers = []
const files = fs.readdirSync(dirPath)
for(const file of files) {
const isDirectory = fs.statSync(path.join(dirPath, file)).isDirectory()
if(isDirectory) {
routers = [...routers, ...scanDirForRouters(path.join(dirPath, file), name file)]
}
else if(file === "router.js") {
routers.push(`import ${name}Router from ${path.join(dirPath, file)}`)
}
}
return routers
}
let allRouters = scanDirForRouters(path.join(path.dirname("."), "modules"))
So if I do a console.log(allRouters) it gives me :
[
'import SomeModuleRouter from modules/SomeModule/Router.js',
'import SomeOtherModuleSubModuleRouter from modules/SomeOtherModule/SubModule/Router.js'
]
So i wish there is a way to execute these command in my script now ... or maybe another way to do it?
Thanks a lot
CodePudding user response:
You could use require
instead. I implemented it by replacing the routers.push
line :
function scanDirForRouters (dirPath, name = "") {
let routers = []
const files = fs.readdirSync(dirPath)
for(const file of files) {
const isDirectory = fs.statSync(path.join(dirPath, file)).isDirectory()
if(isDirectory) {
routers = [...routers, ...scanDirForRouters(path.join(dirPath, file), name file)]
}
else if(file === "router.js") {
require(`${path.join(dirPath, file)}`)
}
}
return routers
}
let allRouters = scanDirForRouters(path.join(path.dirname("."), "modules"))
CodePudding user response:
Thanks to @joprocoorp i found the answer using directly the import function in the loop.
This is my code :
import fs from "fs"
import path from "path"
async function scanDirForRouters (dirPath, name = "") {
let routers = []
const files = fs.readdirSync(dirPath)
for(const file of files) {
const isDirectory = fs.statSync(path.join(dirPath, file)).isDirectory()
if(isDirectory) {
routers = [...routers, ...(async scanDirForRouters(path.join(dirPath, file), name file))]
}
else if(file === "router.js") {
const router = await import(`./${path.join(dirPath, file)}`)
routers.push(router)
}
}
return routers
}
let allRouters = await scanDirForRouters(path.join(path.dirname("."), "modules"))
then I can make a loop on the routers and do whatever i want :)