我是Node.js的新手,正在使用它来构建服务器。
我认为我遇到语法问题。
我安装了babel,因此可以使用ES6语法,因此可以使用import语句,而不需要。
一切正常,直到我尝试从router.js文件导入路由器。
1。安装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);
我遇到以下错误:
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...
我不确定我在这里想念的是什么建议。
答案 0 :(得分:0)
之所以会这样,是因为您的路由器文件没有被编译到dist文件夹中。我建议您创建一个src目录,并将babel指向该文件夹及其所有内容。