Reputation: 46
This is my server.js file:
const express = require('express');
const connectDB = require('./config/db');
const path = require('path');
const app = express();
// Connect Database
connectDB();
// Init Middleware
app.use(express.json());
// Define Routes
app.use('/api/users', require('./routes/api/users'));
In this code, I have some problem like following.
node:internal/errors:490
ErrorCaptureStackTrace(err);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\Study\DEC\devconnector_mobang\config\db.js from E:\Study\DEC\devconnector_mobang\index.js not supported.
Instead change the require of db.js in E:\Study\DEC\devconnector_mobang\index.js to a dynamic import() which is available in all CommonJS modules.
This error 's reason is just require. So I hope to use both import and require or convert require into import. I have strived the some way.
import express from "express";
import connectDB from "./config/db.js";
import path from "path";
// Define require
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const app = express();
// Connect Database
connectDB();
// Init Middleware
app.use(express.json());
const user = require("./config/default");
app.use("/api/users", user);
In here, it can't read this.
import connectDB from "./config/db.js";
But it can read this.
import connectDB from "./config/default.json";
I hope to help you for me to this problem. Thanks.
I hope to solve this problem
Upvotes: 0
Views: 951
Reputation: 29
As per my knowledge, you can use both import and require in a node project but not in the same file.
For example if you are using type: commonjs
then you can add extension .mjs
to import modules in that file.
But if you are using type: module
then you can import and use createRequire
method:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// Now you can use require
const express = require('express');
Upvotes: 1
Reputation: 46
I have this problem solved. This problem is depended node version. Node 16 and Node 20 is definitely different. My node used version 20. I change it version 16 using nvm. Npm install is success and require is normal. Thanks
Upvotes: 0