Home > Mobile >  Converting CommonJS to ES modules
Converting CommonJS to ES modules

Time:03-14

I'm doing coding as a hobby and currently working on a new NodeJS project. With my limited knowledge I have the feeling that working with ES Modules is the future (correct me if I'm wrong). Therefore I would like to re-write some CommonJS scripts that I have into ES Modules.

I'm stuck on the following line trying to convert it: require('./app/routes/routes')(app) (I don't understand what the "(app)" part does at the end).

routes.js:

module.exports = app => {
    const recipe = require('../controllers/recipe-controller.js');
    var router = require('express').Router();
    // Create a new Recipe
    router.post('/recipe', recipe.create);
    app.use('/api/recipes', router);
  };

server.js:

import express from 'express'
import db from './app/models/index'

const app = express();

app.get('/', (req, res) => {
  res.json({ message: 'Welcome to bezkoder application.' });
});
require('./app/routes/routes')(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

CodePudding user response:

This line:

require('./app/routes/routes')(app)

is importing a function and then calling it. It is logically the same as:

const init = require('./app/routes/routes');
init(app);

So, to translate this to ESM, you change your routes module to export a named function. You can then import that named function and then call it (pass app to it).

routes.js

import express from 'express';
import recipe from '../controllers/recipe-controller.js';

export function init(app) {
    // Create a new Recipe
    const router = express.Router();
    router.post('/recipe', recipe.create);
    app.use('/api/recipes', router);
}

server.js

import express from 'express'
import db from './app/models/index'
import init from './app/routes/routes';

const app = express();

app.get('/', (req, res) => {
  res.json({ message: 'Welcome to bezkoder application.' });
});

init(app);

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
  • Related