简体   繁体   中英

Unable to import module in nodejs using ES6 Modules

I have just started learning Node.js and i was trying to connect my application to MongoDB database. Here Server.js is my main file with just two line

import { connectMongoDB } from "./config/db";
connectMongoDB();

and i was trying to import my function connectMongoDB from file db.js, here is the content of db.js

import config from "config";
import mongoose from "mongoose";

const mongoDBUri = config.get("mongoDBUri");
export const connectMongoDB = async () => {
  try {
    await mongoose.connect(mongoDBUri, {
      useNewUrlParser: true,
    });
    console.log("MongoDB connected");
  } catch (error) {
    console.log(
      "[Error] MongoDB did not get connected due to issue " + error.message
    );
    process.exit(1);
  }
};

location of file seems correct to me在此处输入图片说明

I tried using require instead of import and it worked fine. Error thrown -

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\bisht\Project\DHH\dhh\config\db' imported from C:\Users\bisht\Project\DHH\dhh\server.js
[0] Did you mean to import ../config/db.js?
[0]     at finalizeResolution (internal/modules/esm/resolve.js:259:11)
[0]     at moduleResolve (internal/modules/esm/resolve.js:636:10)
[0]     at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:726:11)
[0]     at Loader.resolve (internal/modules/esm/loader.js:97:40)
[0]     at Loader.getModuleJob (internal/modules/esm/loader.js:243:28)
[0]     at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:47:40)
[0]     at link (internal/modules/esm/module_job.js:46:36) {
[0]   code: 'ERR_MODULE_NOT_FOUND'

Did you try running that function in an async context?

For instance:

import { connectMongoDB } from "./config/db";
    
(async () => {
    await connectMongoDB();
})();

There is a difference between module.exports and export take a look at: module.exports vs. export default in Node.js and ES6 At your db.js file, try to change the function exporting as below:

exports.connectMongoDB = async () => {
  try {
    await mongoose.connect(mongoDBUri, {
      useNewUrlParser: true,
    });
    console.log("MongoDB connected");
  } catch (error) {
    console.log(
      "[Error] MongoDB did not get connected due to issue " + error.message
    );
    process.exit(1);
  }
};

i went through the documentation of Node and found out that when we are using ES6 to import modules then we need to define our file with extension ".mjs" instead of just ".js" and while importing the function i also mentioned the extension like this - import { connectMongoDB } from "./config/db.mjs"; and it worked fine

By default, Node JS uses modules according to the CommonJS standard. import - is an ES6 standard. You need to configure package.json for ES6 operation. Add a pair: "type": "module". example:

{
  "name": "index.js",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": ""
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM