我无法运行节点src / index.js,它会引发错误。 但是nodemon没问题。如何运行其生产版本?
PS D:\Development\server\Image hosting\node-express-server-rest-api-master> node src/index.js
D:\Development\server\Image hosting\node-express-server-rest-api-master\src\index.js:2
import cors from 'cors';
SyntaxError: Cannot use import statement outside a module
这是一个非常简单的项目和文件:我尝试了“ type”:“ module”,但是它引发了新的错误。 什么都没做,尽管这只是一个示例项目
package.json :
{
"name": "node-express-server-rest-api",
"version": "0.1.0",
"description": "Node imgs hosting",
"scripts": {
"start": "nodemon --exec babel-node src/index.js",
"test": "echo \"No test specified\" && exit 0",
"production": "NODE_ENV=production node src/index.js",
"win-prod": "set NODE_ENV=production && node src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.11.6",
"@babel/node": "^7.0.0",
"@babel/preset-env": "^7.1.6",
"@babel/register": "^7.0.0"
},
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"follow-redirects": "^1.13.0",
"mkdirp": "^1.0.4",
"uuid": "^7.0.3"
}
}
index.js
require('dotenv/config');
import cors from 'cors';
import express from 'express';
import routes from './routes';
const bodyParser = require("body-parser");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
// req.context = {
// models,
// me: models.users[1],
// };
next();
});
app.use('/upload', routes.upload);
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
答案 0 :(得分:0)
我将答案发布在这里。
添加此模块:npm i esm
在根文件夹下再添加一个文件 我将其命名为main.js:
require = require("esm")(module /*, options*/ )
module.exports = require("./src/index.js")
更改package.json启动脚本 从这个:
"win-prod": "set NODE_ENV=production && node -r src/index.js"
对此:
"win-prod": "set NODE_ENV=production && node -r esm main.js"