Search code examples
node.jsexpressecmascript-6es6-modules

Using inline import in Express use


I am switching my project to ES6 and have been replacing all inline require with import. Replacing the top level require was no issue but when I try to replace the inline require, I get TypeError: app.use() requires a middleware function

// We need these modules to be present.
import path from "path";
import dotEnv from "dotenv";
import express from "express";
import { fileURLToPath } from 'url';
import connectToDatabase from "./database.js";
import morganMiddleware from "./middlewares/morgan.middleware.js";

// Initialise exress
const app = express();

// Initialise dotEnv;
dotEnv.config();

// Define file and directory path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Load environment variables
const PORT = process.env.PORT || 1313;

// Properly parse the json and urlencoed data
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// Add the morgan middleware
app.use(morganMiddleware);

// When we respond with a json object, indent every block with 4 spaces.
app.set("json spaces", 4);

// Where should we look for the static files
app.use(express.static(path.join(__dirname, "../public")));

//Load the different routes
app.use(import("./controllers/index.js"));

// Connect to database
connectToDatabase();

// Custom Error handling
app.use((req, res) => {
   res.status(404).json({
      type: "error",
      message: "404: Page not Found"});
});

app.use((error, req, res, next) => {
   res.status(500).json({
      type: "error",
      message: "500: Internal Server Error"});
});

// Start the server
app.listen(PORT, () => {
   console.log(`Server is running on port ${PORT}`);
});

Does anyone know what's going here?

This is what in the controllers/index.js file

// Loading the modules
import { Router } from "express";

const router = Router()

// Load the models
import ProjectsData, { addProject } from "../models/projects.js";

router.post("/", (req, res) => {
    res.send("Cool. We are working. Now you can proceed to cry.");
});

export default router;

Solution

  • In my opinion, move the import up to the others since you're importing it every time anyway.

    import indexController from "./controllers/index.js"

    app.use(indexController)

    But if you really need to import something inline, here's the documentation. But i'll give you an example.

    All inline imports returns promises and needs to be awaited. Also, when you're writing just import('...') it expects a default export, which you don't have in that specific file. So here's how you'd solve your problem.

    app.use((await import("./controllers/index.js")).default)