英文:
Unsure how to fix "SyntaxError: Cannot use import statement outside module" error in nodejs/expressjs even using "type": "module"
问题
我在这里遇到了一个错误,因为我在一个名为 s3.js
的文件中引入了 aws-sdk
,该文件位于后端文件夹的根目录,与我的 server.js
文件在同一级别:
import aws from 'aws-sdk'
^^^^^^
SyntaxError: Cannot use import statement outside a module
当我在 package.json
文件中添加了 "type": "module"
后,现在我在所有的 require
语句中都会遇到此错误:
require('dotenv').config()
^
ReferenceError: require is not defined in ES module scope, you can use import instead
这是我的 s3.js
和 server.js
代码:
s3.js
import aws from 'aws-sdk'
const region = process.env.AWS_REGION
const bucketName = process.env.AWS_NAME
const accessKeyId = process.env.AWS_ACCESS_KEY_ID
const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY_ID
const s3 = new aws.S3({
region,
accessKeyId,
secretAccessKey,
signatureVersion: 'v4'
})
export async function generateUploadURL() {
const imageName = "random name"
const params = ({
Bucket: bucketName,
Key: imageName,
Expires: 60
})
const uploadURL = await s3.getSignedUrlPromise('putObject', params)
return uploadURL
}
server.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const projectRoutes = require('./routes/projects')
// import aws s3 server code
const s3 = require("./s3.js")
const bodyParser = require("body-parser")
// express app
const app = express()
// middleware
app.use(express.json())
app.use((req, res, next) => {
console.log(req.path, req.method)
next()
})
// image upload
app.get('/api/upload', (req, res) => {
res.json({
t: "sdfsd"
})
})
// routes
app.use('/api/projects', projectRoutes)
// connect to db
mongoose.connect(process.env.MONGO_URI)
.then(() => {
// listening to requests once connected to DB
app.listen(process.env.PORT, () => {
console.log('Connected to DB, listening on port 4000')
})
})
.catch((error) => {
console.log(error)
})
我不确定如何修复语法错误而不替换所有的 require
语句,如果我替换所有的语句会解决吗?另外,使用 require
和 import
之间有什么区别?
英文:
I'm struggling to fix this error I'm getting here because of an aws-sdk
import I'm making in a file called s3.js
that's in the root directory of my backend folder on the same level as my server.js
file:
import aws from 'aws-sdk'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1177:20)
at Module._compile (node:internal/modules/cjs/loader:1221:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1311:10)
at Module.load (node:internal/modules/cjs/loader:1115:32)
at Module._load (node:internal/modules/cjs/loader:962:12)
at Module.require (node:internal/modules/cjs/loader:1139:19)
at require (node:internal/modules/helpers:121:18)
at Object.<anonymous> (/Users/simerusmahesh/Code/queens_cpp/Queens-Community-Partnership-Project/backend/server.js:8:12)
at Module._compile (node:internal/modules/cjs/loader:1257:14)
Node.js v20.3.1
[nodemon] app crashed - waiting for file changes before starting..
When I do add "type": "module"
in my package.json
file, now I'm getting this error for all my require
statements:
require('dotenv').config()
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/simerusmahesh/Code/queens_cpp/Queens-Community-Partnership-Project/backend/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///Users/simerusmahesh/Code/queens_cpp/Queens-Community-Partnership-Project/backend/server.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:192:25)
at async DefaultModuleLoader.import (node:internal/modules/esm/loader:246:24)
at async loadESM (node:internal/process/esm_loader:40:7)
at async handleMainPromise (node:internal/modules/run_main:66:12)
Node.js v20.3.1
[nodemon] app crashed - waiting for file changes before starting...
Here is my s3.js and server.js code:
s3.js
import aws from 'aws-sdk'
const region = process.env.AWS_REGION
const bucketName = process.env.AWS_NAME
const accessKeyId = process.env.AWS_ACCESS_KEY_ID
const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY_ID
const s3 = new aws.S3({
region,
accessKeyId,
secretAccessKey,
signatureVersion: 'v4'
})
export async function generateUploadURL() {
const imageName = "random name"
const params = ({
Bucket: bucketName,
Key: imageName,
Expires: 60
})
const uploadURL = await s3.getSignedUrlPromise('putObject', params)
return uploadURL
}
server.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const projectRoutes = require('./routes/projects')
// import aws s3 server code
const s3 = require("./s3.js")
const bodyParser = require("body-parser")
// express app
const app = express()
// middleware
app.use(express.json())
app.use((req, res, next) => {
console.log(req.path, req.method)
next()
})
// image upload
app.get('/api/upload', (req, res) => {
res.json({
t: "sdfsd"
})
})
// routes
app.use('/api/projects', projectRoutes)
// connect to db
mongoose.connect(process.env.MONGO_URI)
.then(() => {
// listening to requests once connected to DB
app.listen(process.env.PORT, () => {
console.log('Connected to DB, listening on port 4000')
})
})
.catch((error) => {
console.log(error)
})
I'm not sure how to fix the Syntax error without replacing all my require statements, if I do replace them all will this fix it? Additionally, what's the difference between using require and import?
答案1
得分: 1
从你的 package.json 文件中删除 "type": "module" 行。
将文件 s3.js 重命名为 .cjs 扩展名,例如 s3.cjs。
将导入语句 import aws from 'aws-sdk' 更改为 const aws = require('aws-sdk')。
英文:
Remove the "type": "module" line from your package.json file. <br>
Rename the file s3.js to have the .cjs extension, e.g., s3.cjs. <br>
Change the import statement import aws from 'aws-sdk' to const aws = require('aws-sdk')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论