获取connect-redis 7.0.1的错误[ERR_REQUIRE_ESM]

nhhxz33t  于 12个月前  发布在  Redis
关注(0)|答案(1)|浏览(222)

节点版本:16.20.2connect-redis版本:7.0.1 esm版本:3.2.25 redis版本:3.0.2 express-session版本:1.17.3

我得到ERR_REQUIRE_ESM错误为connect-redis在我的节点应用程序.我已经尝试安装不同版本的redis,connect-redis和esm.但没有为我工作.请帮助我与解决方案.为了您更好地理解我在这里分享相关的代码块.

错误:

/Users/user/bidyaguru/bg-cpanel-app/server.js:1
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/user/project/myapp/node_modules/connect-redis/dist/esm/index.js not supported.
Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/user/project/myapp/server.js:1)
    at Generator.next (<anonymous>) {
  code: 'ERR_REQUIRE_ESM'
}

字符串
我的package.json文件:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "server": "node -r esm server.js",
    "dev": "nodemon -r esm server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "connect-redis": "^7.1.0",
    "dotenv": "^16.3.1",
    "esm": "^3.2.25",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "mongoose": "^6.9.2",
    "redis": "^3.0.2"
  }
}


我的server.js文件:

import express from 'express';
import dotenv from 'dotenv';
import expressSession from'express-session';
import {createClient} from "redis";
import RedisStore from "connect-redis";

import connectDB from './config/db';

dotenv.config();
connectDB();
const app = express();
app.use(express.json());

app.get('/_status', (req, res) => {
  res.send('Server is okay');
});

// Initialize redis client.
const redisHost = process.env.REDIS_HOST
const redisPort = process.env.REDIS_PORT || 6379;
let redisClient = createClient(redisHost, redisPort);
redisClient.connect().catch(console.error)

// Initialize redis store.
let redisStore = new RedisStore({
  client: redisClient,
  prefix: "myapp:",
})

// Initialize redis sesssion storage.
app.use(
  expressSession({
    store: redisStore,
    resave: false,
    saveUninitialized: false,
    secret: "secret",
    cookie: { maxAge: (1000 * 60 * 60 * 24 * 30) }
  })
);

const PORT = process.env.PORT || 3001;
app.listen(PORT, (err) => {
  if (err) { process.exit(1); }
  console.log(`Service is running at port ${PORT}`);  
});

q43xntqr

q43xntqr1#

看起来你想使用ESM,所以使用Node.js版本提供的原生支持。
1.重新启动esm软件包。
1.在package.json文件中设置"type": "module"
1.从npm脚本中删除-r esm
1.重新配置您的相对导入,以包含.js扩展,例如import connectDB from './config/db.js';
现在尝试运行dev npm run dev
您可以在GitHub上的busmap存储库中看到使用connect-redis的ESM的工作示例。

相关问题