0

I am trying to build a basic Express api and am running in to an odd module not found error. Before introducing TypeScript to my project, I never got this error. This has been quite frustrating to resolve. I appreciate any suggestions on why I am getting this error and how to resolve.

server.ts

import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
//import * as api from "api"; also tried this

const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

app.use('/api', require('./api'));

app.use('*', (req, res, next) => {
    let error = new Error('404: not found');
    next(error);
});

app.use((error, req, res, next) => {
    res.status(500).send({
        error: {
            message: error.message
        }
    });
});

const port = 3000;

app.listen(port, () => {
    console.log('listening on port', port);
});

module.exports = app;

api/api.ts

import express from "express";

const router = express.Router();

router.use('/', (req, res, next) => {
   res.send('cool');
});

module.exports = router;

1 Answer 1

1

With typescript, we don't use module.exports but export directly like so:

import express from "express";

export const router = express.Router();

router.use('/', (req, res, next) => {
   res.send('cool');
});

Then we can get the router with

import {router} from './api'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.