Home > OS >  how to convert the following syntax into an es6 syntax?
how to convert the following syntax into an es6 syntax?

Time:05-13

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()

CodePudding user response:

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"

CodePudding user response:

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";

CodePudding user response:

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

  • Related