'how to convert the following syntax into an es6 syntax?

I have this statement to modularize my express.js api's:

app.use("/api/users", require("./routes/api/users"));

How to write it using import statement?

inside "./routes/api/users", I am exporting express.Router()



Solution 1:[1]

Inside users.js use const router = express.Router() and then export default router At the top of your file write import router from "./routes/api/users"

Solution 2:[2]

You can use default export of es6 in "./routes/api/users" as well although it's not compulsory.

./routes/api/users


import { Router } from "express";

const router = Router();

router.get("/", (req, res)=> {
    // 
});

export default router;

And then import it using the following syntax.

import UserRoutes from "./routes/api/users";

Solution 3:[3]

I guess you are using node JS. So, basically nodeJS uses CommonJS by default, so you are using require() statement which is a part of CommonJS. To use the latest ES6 import export feature, go to package.json and add the following inside of the JSON container:

    "type": "module",

Note that this must be in the first object, not nested inside of anything. You can write it below the version ( for ease of understanding ).

Hope it helps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shahryar_Jahanshahloo
Solution 2 Amit
Solution 3 Asim Koirala