Reputation: 12538
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;
Upvotes: 0
Views: 398
Reputation: 114767
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'
Upvotes: 1