1

In my Node project I'm using es6 imports instead of commonjs' require().

I've found this snippet to map through a folder and insert the files as the second argument to app.use():

readdirSync('./routes').map(r => app.use('/', require('./routes/' r)));

Can I translate this to es6 import syntax?

AndyOh
  • 87
  • 1
  • 9
  • 3
    ES2020 `import()` syntax is asynchronous, so no, there is no 1:1 equivalent. I'd rather recommend spelling out the imports, or generate that file in a build step, but if you really want you can still dynamically register routes. Have you tried it? – Bergi Jul 05 '22 at 12:33
  • Thanks for your comment @Bergi. No, I am not familiar with dynamically registered routes. An alternative I've seen and will probably go with is to collect all routes files in a single file and import that into my main app.js file. – AndyOh Jul 06 '22 at 12:46
  • 1
    By "dynamically registered route" I mean the `app.use('/', require(someVariable))` that you're already using. You can of course do `app.use('/', (await import(someVariable)).default)` as well, but make sure to consider what happens if the server is opened before all routes are registered. – Bergi Jul 06 '22 at 13:48
  • Ah, yes of course. Thanks for the suggestion but if this isn't a common/recommended pattern, I think I will revert to something that is (e.g. importing all routes into one file, then exporting that to my main server file). – AndyOh Jul 07 '22 at 12:25
  • 1
    It's fine, it's just a bit more complicated than manually importing and registering all the routes – Bergi Jul 07 '22 at 13:24
  • Can you explain this syntax (with an example maybe)? `await import(someVariable).default` – AndyOh Jul 09 '22 at 16:40
  • `import(…)` returns a promise that will fulfill with the namespace object of the module. Access the route handler as a property on it under the name that you exported it. – Bergi Jul 09 '22 at 16:57

0 Answers0