Skip to content

Commit

Permalink
Feature/add prefix option (#15)
Browse files Browse the repository at this point in the history
* provided prefix option

* readme typo

Co-authored-by: Bobby Piper <bobby.piper@agrovista.co.uk>
  • Loading branch information
bobbypiper and bobbypiperagrovista authored Nov 21, 2022
1 parent ccb7018 commit 6833036
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Add the plugin to the plugins section, and configure the rule options.
...
"no-relative-import-paths/no-relative-import-paths": [
"warn",
{ "allowSameFolder": true, "rootDir": "src" }
{ "allowSameFolder": true, "rootDir": "src", "prefix": "" }
]
...
```
Expand Down Expand Up @@ -85,3 +85,24 @@ import Something from "components/something";
// ^- no 'src/' prefix is added
```

### `prefix`

Useful when auto-fixing and a prefix should be included in the absolute path.

Examples of code for this rule:

```js
// when not configured:
import Something from "../../components/something";

// will result in
import Something from "src/components/something";
```

```js
// when configured as { "prefix": "@" }
import Something from "../../components/something";

// will result in
import Something from "@/components/something";
```
15 changes: 9 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,16 @@ function isSameFolder(path) {
return path.startsWith("./");
}

function getAbsolutePath(relativePath, context, rootDir) {
return path
function getAbsolutePath(relativePath, context, rootDir, prefix) {
return [
prefix,
...path
.relative(
context.getCwd() + (rootDir !== '' ? path.sep + rootDir : ''),
path.join(path.dirname(context.getFilename()), relativePath)
)
.split(path.sep)
.join("/");
].join("/");
}

const message = "import statements should have an absolute path";
Expand All @@ -35,9 +37,10 @@ module.exports = {
fixable: "code",
},
create: function (context) {
const { allowSameFolder, rootDir } = {
const { allowSameFolder, rootDir, prefix } = {
allowSameFolder: context.options[0]?.allowSameFolder || false,
rootDir: context.options[0]?.rootDir || '',
prefix: context.options[0]?.prefix || '',
};

return {
Expand All @@ -50,7 +53,7 @@ module.exports = {
fix: function (fixer) {
return fixer.replaceTextRange(
[node.source.range[0] + 1, node.source.range[1] - 1],
getAbsolutePath(path, context, rootDir || '')
getAbsolutePath(path, context, rootDir || '', prefix)
);
},
});
Expand All @@ -63,7 +66,7 @@ module.exports = {
fix: function (fixer) {
return fixer.replaceTextRange(
[node.source.range[0] + 1, node.source.range[1] - 1],
getAbsolutePath(path, context, rootDir || '')
getAbsolutePath(path, context, rootDir || '', prefix)
);
},
});
Expand Down

0 comments on commit 6833036

Please sign in to comment.