Skip to content

Commit 4f697c9

Browse files
committed
feat: allow to alias also subpaths
1 parent d0a7d59 commit 4f697c9

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,14 @@ If you have a special project setup that does not have a babel config in the pro
125125
}
126126
```
127127

128+
By default, the plugin will convert parent paths to aliases (like `../model/foo`), but will keep subpath imports relative. You can change that to also convert subpaths to aliased imports by passing the `aliasForSubpaths` option to the rule like so:
129+
130+
```json
131+
"rules": {
132+
"@dword-design/import-alias/prefer-alias": ["error", { "aliasForSubpaths": true }]
133+
}
134+
```
135+
128136
<!-- LICENSE/ -->
129137
## Contribute
130138

src/rules/prefer-alias.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,11 @@ export default {
9797
options,
9898
);
9999

100-
if (!(importWithoutAlias |> isParentImport) && hasAlias) {
100+
if (
101+
!(importWithoutAlias |> isParentImport) &&
102+
hasAlias &&
103+
!options.allowSubpathWithAlias
104+
) {
101105
return context.report({
102106
fix: fixer =>
103107
fixer.replaceTextRange(
@@ -118,7 +122,10 @@ export default {
118122
schema: [
119123
{
120124
additionalProperties: false,
121-
properties: { alias: { type: 'object' } },
125+
properties: {
126+
alias: { type: 'object' },
127+
aliasForSubpaths: { default: false, type: 'boolean' },
128+
},
122129
type: 'object',
123130
},
124131
],

src/rules/prefer-alias.spec.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,23 @@ export default tester(
7474
output: "import foo from './foo'",
7575
});
7676
},
77+
aliasForSubpaths: async () => {
78+
await outputFiles({
79+
'.babelrc.json': JSON.stringify({
80+
plugins: [
81+
[
82+
packageName`babel-plugin-module-resolver`,
83+
{ alias: { '@': '.' }, aliasForSubpaths: false },
84+
],
85+
],
86+
}),
87+
'foo.js': '',
88+
});
89+
90+
expect(
91+
lint("import foo from '@/foo'", { filename: 'sub/index.js' }).messages,
92+
).toEqual([]);
93+
},
7794
'custom alias': async () => {
7895
await outputFiles({ 'foo.js': '', 'package.json': JSON.stringify({}) });
7996

0 commit comments

Comments
 (0)