简体   繁体   中英

Node.js - Error: Cannot find module './router'

I'm new to Node.js and I'm using it to build server.

I think I'm having a syntax problem.

I installed babel so I can use ES6 syntax and so I can use import statement and not require.

Everything worked fine until I tried to import router from router.js file.

1. Installation of babel

`npm install --save-dev @babel/cli @babel/core @babel/preset-env`

2. $ touch .babelrc

{
  "presets": ["@babel/preset-env"]
}

Package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "Hotel management server",
  "main": "index.js",
  "scripts": {
    "build": "babel index.js -d dist",
    "start": "npm run build && nodemon dist/index.js"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongoose": "^5.5.12",
    "morgan": "^1.9.1",
    "nodemon": "^1.19.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/preset-env": "^7.4.5"
  }
}

router.js

module.exports = function(app){
    app.get('/', function(req, res, next){
        res.send(['water', 'phone', 'paper']);
    });
}

index.js

import express from 'express';
import http from 'http';
import bodyParser from 'body-parser';
import morgan from 'morgan';
const app = express();
import router from './router';

//App setup
app.use(morgan('combined')); 
app.use(bodyParser.json({type: '*/*'})); 
router(app);


const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('server listenining on ', port);

I'm getting the following error:

Error: Cannot find module './router'
    at Function.Module._resolveFilename (module.js:543:15)
    at Function.Module._load (module.js:470:25)
    at Module.require (module.js:593:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/teabuzov/Desktop/sts/hotelapp/hotel-management/server/dist/index.js:11:38)
    at Module._compile (module.js:649:30)
    at Object.Module._extensions..js (module.js:660:10)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:501:12)
    at Function.Module._load (module.js:493:3)
[nodemon] app crashed - waiting for file changes before starting...

I'm not sure what am I missing here any advice would be appreciated.

The reason this is happening is because your router file is not being compiled into your dist folder. I would suggest you create a src directory and point babel to that folder and all its contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM