A resolver in order to shorten deeply nested relative path expression.
In monorepo structure or complex directory hierarchy, we used to exhausted by deeply nested import expression. (e.g. import ... from '../../../../package.json'
in packages/frontend/components/button/index.jsx
)
-
babel-plugin-module-resolver
It has a risk of name collision with existing modules by indirect deep dependencies. because it allows using any name as an alias. -
babel-plugin-root-import
It allows only one character as an alias name. (e.g.~
is allowed, but~~
is not)-
eslint-import-resolver-babel-plugin-root-import
It requiresbabel-plugin-root-import@^5
. but latest version ofbabel-plugin-root-import@6
is released.
-
-
babel-plugin-hash-resolve
It requires off some option ofeslint-plugin-import
. (e.g.import/no-unresolved
,import/extensions
)
$ npm install --save-dev @cichol/alias-mapper
If import ... from '(frontend)/application'
expression in backend/server.js
file. that will be transformed like const ... = require('../frontend/releases/application')
.
{
"plugins": [
[
"module:@cichol/alias-mapper",
{
"rootDirs": [
"sources"
],
"aliases" {
"models": "sources/backend/models"
}
}
]
]
}
Write or append above codes into your Babel configuration file. (e.g. babel.config.js
, .babelrc(.js(on)?)?
)
Babel integration has to match to output directories. (e.g. dist
, out
, build
, ...)
If you want to integrate with ESLint, you have to ensure eslint-plugin-import
installed. and then, set resolver to your configuration file.
{
"settings": {
"import/resolver": {
"@cichol/alias-mapper": {
"rootDirs": [
"sources"
],
"aliases" {
"models": "sources/backend/models"
}
}
}
}
}
Write or append above codes into your ESLint configuration file. (e.g. .eslintrc(.js(on)?|.ya?ml)?
)
ESLint integration has to match to source directories. (e.g. src
, ...)
In Visual Studio Code, all JavaScript files are analyzed by internal TypeScript language handler. so, you can just write jsconfig.json
file or tsconfig.json
for TypeScript project.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"(frontend)/*": "sources/frontend/*",
"(backend)/*": "sources/backend/*",
"(models)/*": "sources/backend/models/*"
}
},
"include": ["sources"]
}
Visual Studio Code integration has to wrap alias name with parentheses and match to source directories.
After the integration process, you can write code with aliased scopes. an alias name has to wrapped by parentheses for avoiding name collision with existing modules by indirect deep dependencies.
Before
- import logger from '../../../../common/logger';
After
+ import logger from '(common)/logger';