Say “Goodbye” Relative Imports in NodeJS Projects
If you have been working on NodeJS projects for a while, I am pretty sure that you have ever seen “../../some/deep/import-path” syntax. I think these make you crazy with your code (or your partner 😅).
Can we refactor to make our codebase more prettier and clean? 🤔🧐
Absolutely YES! 😁
We have many ways to do it but there may have risks and difficulties for each way. (You can try yourself with some references at the end).
The way I mention in this article is using the jsconfig.json file and babel-cli.
Code example
Where is relative import? Be patient! It will appear below. 😄
So how can I refactor to
import { sum, subtract } from 'lib/math';
Main steps
1. Create “jsconfig.json” file in the root path of your project.
If you do not know what it is you can refer to vscode docs.
The most important thing I want to mention is “compilerOptions.baseUrl”. It stands for the main directory to look for the non-relative module name.
I put the source code under “src”, so compilerOptions.baseUrl = “./src” 😎
2. Configure babel
Run:
npm install --save-dev @babel/core @babel/cli @babel/preset-env babel-plugin-module-resolver
Package “babel-plugin-module-resolver” helps us to add new root directory to look up modules instead of having only one folder named “node_modules”.
Create new file named ./.babelrc.js to contain babel configuration
Add new scripts to transpile source code in “package.json”
Use babel-cli to transpile source code from a folder named src to dist and copy other files if it is not matched to transpile.
Result
Run “yarn build” and check the result
You can see that babel can transpile our absolute path to the relative one.
Surprise! 😁 From now on, you import the module via absolute path and use vscode to navigate to definition.
If you face any issues, do not hesitate to ask me. Anyway, you can refer to my example source code on GitHub if you want. 😊
Thank you and see you in the next article! 😉
References:
- Better local require() paths for Node.js
- Create react app absolute imports
- Webpack resolve module