'Import module with absolute path using jsconfig.json not working in Node JS
It is difficult to refer the modules using relative path in the project. To achieve this we tried to using jsconfig.json on the client (react) project to refer from the absolute path. Below is my jsconfig.json file. It is working fine.
{
"compilerOptions": {
"baseUrl": "./src"
}
}
I am not able to achieve the same on server ( node js ) project. Getting the error messages
cannot find module
Any reference would be appreciated.
Solution 1:[1]
You can use baseUrl
along with paths
to fix the errors.
Paths allow us to aggregate a list directories under a predefined name and drastically reduce the length of the imports.
Here is a template on how to setup them your jsconfig.json
.
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@routes/*": [
"./routes/*"
],
"@models/*": [
"./models/*"
],
"@datetime/*": [
"./utils/datetime/*"
]
}
}
}
We are aggregating all the files in the models folder under the name @models. The same is the case for routes and datetime. We would be able to reference the folders using @routes, @models, and @datetime in the import statement.
So, after you've setup your jsconfig, you need to change the relative paths to absolute paths. For example:
server.js
// Before jsconfig
import adminRoutes from "../../src/routes/admin"
// After jsconfig
import adminRoutes from "@routes/admin"
I hope it helps!
Read the source for more details.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |