Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

facing problem while importing files in nodejs

I don't know what's going wrong with these extensions, when I provide the extension ".js" the app runs fine but it gives a warning on that line saying Unexpected use of file extension "js" for "./models/user.js", but when I remove the extension the whole app crashes and says Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'F:\React\AuthenticationApp\backend\src\models\user' imported from F:\React\AuthenticationApp\backend\src\index.js, I know that files can be imported in node.js without providing the extension but I just know-how here's my code

    // eslint-disable-next-line no-unused-vars
import express from 'express'
import User from './models/user'

import './db/mongoose'

const app = express()
const port = 4000

app.use(express.json())

app.post('/users', (req, res) => {
  const user = new User(req.body)

  user
    .save()
    .then(() => {
      res.send(user)
      console.log(user)
    })
    .catch((e) => {
      res.status(401).send(e)
    })
})

app.listen(port, () => {
  console.log(`Server is up on ${port}`)
})

and this is package.json

   {
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "type": "module",
  "scripts": {
    "build": "babel ./src --out-dir ./build",
    "start": "nodemon --exec babel-node src/index.js",
    "dev": "nodemon src/index.js",
    "lint": "eslint ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.13.16",
    "@babel/core": "^7.13.16",
    "@babel/node": "^7.13.13",
    "@babel/preset-env": "^7.13.15",
    "@babel/runtime": "^7.13.17",
    "eslint": "^7.25.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-prettier": "^3.4.0",
    "nodemon": "^2.0.7",
    "prettier": "^2.2.1"
  },
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.12.6",
    "validator": "^13.6.0"
  }
}
like image 953
Neel Chavan Avatar asked Feb 19 '26 13:02

Neel Chavan


1 Answers

Adjust your eslint config with this rule:

"rules": {
    "import/extensions": [
        "error",
        {
            "js": "ignorePackages"
        }
    ]
},

Detailed description of the rule is in this page.

That way a nodejs will successfully run, eslint will not show error.

CommonJS modules are still able to be without extension in 'require' functions.
But you have to specify an extension of ESmodule when using 'import' (except 'Bare specifiers' like 'some-package'), this is according to nodejs docs.

like image 189
Pavlikooo Avatar answered Feb 23 '26 19:02

Pavlikooo