Nodejs运行js报错:Cannot use import statement outside

我无法运行 node 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”,但它抛出了新的错误。尽管这只是一个示例项目,但没有任何效果


包.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"

  }

 }

索引.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}!`),

);


qq_遁去的一_1
浏览 556回答 1
1回答

皈依舞

我会在这里发布答案。添加此模块: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"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript