From 68330363f96161c63e85ad03e3d5161450cf602d Mon Sep 17 00:00:00 2001 From: Bobby Piper Date: Mon, 21 Nov 2022 14:49:08 +0000 Subject: [PATCH] Feature/add prefix option (#15) * provided prefix option * readme typo Co-authored-by: Bobby Piper --- README.md | 23 ++++++++++++++++++++++- index.js | 15 +++++++++------ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c55ec16..8e0c92a 100644 --- a/README.md +++ b/README.md @@ -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": "" } ] ... ``` @@ -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"; +``` \ No newline at end of file diff --git a/index.js b/index.js index 5195d3d..fff3a24 100644 --- a/index.js +++ b/index.js @@ -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"; @@ -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 { @@ -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) ); }, }); @@ -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) ); }, });