Reputation: 1654
Good evening. I'm having a syntax problem, I'm migrating to babel and I have the problem in the following syntax. Require an unnamed module. In the default import of nodejs I can import without naming the exported module and passing the app in, already in babel es6 I could not find something similar, but made it work.
Node default
export
router.get('/',(req, res) => res.send('test'))
module.exports = app => app.use('/test', router)
require()
require('./routes/uploader')(app)
Babel
export
router.get('/',(req, res) => res.send('test'))
export default app => app.use('/test', router)
import
import router from './routes/uploader'
router(app)
In babel I was able to perform the import only by naming and then passing the app inside the router. I researched a lot but I did not find a simpler way. Would you have a better idea to export the router by passing the app on babel?
Upvotes: 1
Views: 179
Reputation: 222750
require
can still be used in Babel if that's the intention.
import router from './routes/uploader'
router(app)
is the way how this is done with ES modules, considering that router
function is ./routes/uploader
default export. It's not specific to Babel.
router
import name is self-documenting and can be debugged in case it's not a function but something else. While require('./routes/uploader')(app)
is a shortcut that is common in Node.js that may be difficult to read and debug.
Would you have a better idea to export the router by passing the app on babel?
import
statement is supposed to be statically analyzed, it doesn't contain code that should be evaluated. There's no other way to export
it, ES module is an object, all exports are object properties, it's either default
or named export.
Though modules can be designed to not require exports to be wrapped with a function.
It can be app
instance that is used across the app. There should be a dedicated module for the app to avoid circular dependencies:
app.js
export default express();
index.js
import app from './app';
import './routes';
app.listen(...);
routes.js
import app from './app';
app.get(...);
Another way that is more popular is to decouple router from app instance. Express routes can be mounted, that's a major benefit:
index.js
import router from './routes';
const app = express();
app.use(router)
app.listen(...);
route.js
const router = express.Router();
router.get(...);
export default router;
There are cases when wrapping export with app => { ... }
is beneficial, but it is not necessary here. Any way, it's a good convention for modules where app
instance is really needed, e.g. to reach app.locals
.
Upvotes: 2