0

Recently i saw a video that i guy was exporting a module in commonjs:

// src/routes/index.js file

module.exports = [
  require('./user'),
  require('./auth'),
  require('./demo')
]
// src/routes/user.js

const exppres = require('express')
const api = express.Router()

api.post('/user' , doSomething())

// src/handler.js

const express = require('express')
const api = require('./routes')
const app = express()

app.use(api) // add all routes

I tried all different ways of doing, like:

export default {
   import "./user",
   import "./auth"
}

and in server layer

import api from './routes'

but nothing works...

Someone knows how to do it?

2 Answers2

1

Try this

module.exports = {
  user:require('./user'),
  auth:require('./auth'),
  demo: require('./demo')
}

Then access them like this

const {user,auth, demo} = require("path to the expoted module")
MUGABA
  • 751
  • 6
  • 7
1

I don't quite understand what you mean by "for its side effects only", because then you wouldn't need to export anything. Importing for side effects only is done like this with ES6 modules:

import './user';
import './auth';
import './demo';

If you wanted to re-export something from these modules, you'd typically write

export * from './user';
export * from './auth';
export * from './demo';

or

export { default as user } from './user';
export { default as auth } from './auth';
export { default as demo } from './demo';

You would not export an array.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • let me give an example. All these imports are routes of a api. I am trying to export all routes in a single file to inject in my express server. I was thinking that i could import them in my application file and use all imported routes. With this example, It makes more clear what am i trying to do? – lucas dellatorre Jul 22 '22 at 14:28
  • Then it's definitely not "for side effects only". Can you show what you are exporting from those modules, and how you'd like to import and use those values in your application file? You can [edit your question](https://stackoverflow.com/posts/73081017/edit) to include more code. – Bergi Jul 22 '22 at 15:10
  • I added more code as you asked for :) – lucas dellatorre Jul 22 '22 at 17:12