将别名 @ 导入重构为相对路径

Refactor aliased @ imports to relative paths

在使用 Webpack、TypeScript 或其他转换 ES 模块导入的工具的模块化环境中,使用路径别名,常见的约定是

使用别名绝对路径转换项目是我经常遇到的问题:

src/foo/bar/index.js

import baz from '@/baz';

相对路径:

src/foo/bar/index.js

import baz from '../../baz';

例如,一个使用别名的项目需要与另一个不使用别名的项目合并,由于风格指南或其他原因,无法将后者配置为使用别名。

这不能通过简单的搜索和替换来解决,手动修复导入路径既繁琐又容易出错。我希望原始 JavaScript/TypeScript 代码库在其他方面保持完整,因此使用转译器对其进行转换可能不是一种选择。

我想用我选择的 IDE (Jetbrains IDEA/Webstorm/Phpstorm) 实现这种重构,但会接受任何其他 IDE (VS Code) 或普通的解决方案Node.js.

如何实现?

来自您链接的post:

The meaning and structure of the module identifier depends on the module loader or module bundler

意思是,对于这个“@”-> 相对导入转换,永远不会有一刀切解决方案。你可以做的是有一些程序可以让你指定@对给定项目意味着什么,那应该是一个相当不错的解决方案!

我想我要解决这个问题的方法是创建一个 codemod 来查看导入语句中包含 @ 的文件,并确定它必须遍历多少个父目录到达用户确定的 root 目录,然后将 @ 符号替换为适当数量的 ../.

完成 codemod/program/script 后,您可以从您选择的编辑器中触发它!

这至少是我解决这个问题的方法(除了还在四处寻找我可以在开始之前应用的预制解决方案!)

将别名导入重新连接到相对路径的三种可能的解决方案:

1。 babel-plugin-module-resolver

使用 babel-plugin-module-resolver,同时忽略其他 babel plugins/presets。

.babelrc:
"plugins": [
  [
    "module-resolver",
    {
      "alias": {
        "^@/(.+)": "./src/\1"
      }
    }
  ]
]

构建步骤:babel src --out-dir dist(在dist中输出,不会就地修改)

处理后的示例文件:
// input                                // output
import { helloWorld } from "@/sub/b"    // import { helloWorld } from "./sub/b";
import "@/sub/b"                        // import "./sub/b";
export { helloWorld } from "@/sub/b"    // export { helloWorld } from "./sub/b";
export * from "@/sub/b"                 // export * from "./sub/b";

对于 TS,您还需要 @babel/preset-typescript 并通过 babel src --out-dir dist --extensions ".ts" 激活 .ts 个扩展。

2。使用 Regex

的 Codemod jscodeshift

来自 MDN docs 的所有相关 import/export 变体都应该得到支持。算法是这样实现的:

1。输入:路径别名映射形式 alias -> resolved path 类似于 TypeScript tsconfig.json paths 或 Webpack 的 resolve.alias:

const pathMapping = {
  "@": "./custom/app/path",
  ...
};

2。遍历所有源文件,例如遍历 src:

jscodeshift -t scripts/jscodeshift.js src # use -d -p options for dry-run + stdout
# or for TS
jscodeshift --extensions=ts --parser=ts -t scripts/jscodeshift.js src

3。对于每个源文件,查找所有导入和导出声明

function transform(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);

  root.find(j.ImportDeclaration).forEach(replaceNodepathAliases);
  root.find(j.ExportAllDeclaration).forEach(replaceNodepathAliases);
  root
    .find(j.ExportNamedDeclaration, node => node.source !== null)
    .forEach(replaceNodepathAliases);
  return root.toSource();
 ...
};

jscodeshift.js:

/**
 * Corresponds to tsconfig.json paths or webpack aliases
 * E.g. "@/app/store/AppStore" -> "./src/app/store/AppStore"
 */
const pathMapping = {
  "@": "./src",
  foo: "bar",
};

const replacePathAlias = require("./replace-path-alias");

module.exports = function transform(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);

  root.find(j.ImportDeclaration).forEach(replaceNodepathAliases);
  root.find(j.ExportAllDeclaration).forEach(replaceNodepathAliases);

  /**
   * Filter out normal module exports, like export function foo(){ ...}
   * Include export {a} from "mymodule" etc.
   */
  root
.find(j.ExportNamedDeclaration, (node) => node.source !== null)
.forEach(replaceNodepathAliases);

  return root.toSource();

  function replaceNodepathAliases(impExpDeclNodePath) {
impExpDeclNodePath.value.source.value = replacePathAlias(
  file.path,
  impExpDeclNodePath.value.source.value,
  pathMapping
);
  }
};

进一步说明:

import { AppStore } from "@/app/store/appStore-types"

创建以下 AST,其 ImportDeclaration 节点的 source.value 可以修改:

4。对于每个路径声明,测试包含路径别名之一的正则表达式模式。

5。获取别名的解析路径并转换为相对于当前文件位置的路径(归功于@Reijo)

replace-path-alias.js (4. + 5.):

const path = require("path");

function replacePathAlias(currentFilePath, importPath, pathMap) {
  // if windows env, convert backslashes to "/" first
  currentFilePath = path.posix.join(...currentFilePath.split(path.sep));

  const regex = createRegex(pathMap);
  return importPath.replace(regex, replacer);

  function replacer(_, alias, rest) {
const mappedImportPath = pathMap[alias] + rest;

// use path.posix to also create foward slashes on windows environment
let mappedImportPathRelative = path.posix.relative(
  path.dirname(currentFilePath),
  mappedImportPath
);
// append "./" to make it a relative import path
if (!mappedImportPathRelative.startsWith("../")) {
  mappedImportPathRelative = `./${mappedImportPathRelative}`;
}

logReplace(currentFilePath, mappedImportPathRelative);

return mappedImportPathRelative;
  }
}

function createRegex(pathMap) {
  const mapKeysStr = Object.keys(pathMap).reduce((acc, cur) => `${acc}|${cur}`);
  const regexStr = `^(${mapKeysStr})(.*)$`;
  return new RegExp(regexStr, "g");
}

const log = true;
function logReplace(currentFilePath, mappedImportPathRelative) {
  if (log)
console.log(
  "current processed file:",
  currentFilePath,
  "; Mapped import path relative to current file:",
  mappedImportPathRelative
);
}

module.exports = replacePathAlias;

3。仅正则表达式搜索和替换

遍历所有来源并应用正则表达式(未彻底测试):

^(import.*from\s+["|'])(${aliasesKeys})(.*)(["|'])$

,其中 ${aliasesKeys} 包含路径别名 "@"。新的导入路径可以通过修改2nd和3rd capture group来处理(路径映射+解析为相对路径)

此变体无法处理 AST,因此可能被认为不如 jscodeshift 稳定。

目前,正则表达式仅支持导入。 import "module-name" 形式的副作用导入被排除在外,好处是 search/replace.

更安全

样本:

const path = require("path");

// here sample file content of one file as hardcoded string for simplicity.
// For your project, read all files (e.g. "fs.readFile" in node.js)
// and foreach file replace content by the return string of replaceImportPathAliases function.
const fileContentSample = `
import { AppStore } from "@/app/store/appStore-types"
import { WidgetService } from "@/app/WidgetService"
import { AppStoreImpl } from "@/app/store/AppStoreImpl"
import { rootReducer } from "@/app/store/root-reducer"
export { appStoreFactory }
`;

// corresponds to tsconfig.json paths or webpack aliases
// e.g. "@/app/store/AppStoreImpl" -> "./custom/app/path/app/store/AppStoreImpl"
const pathMappingSample = {
  "@": "./src",
  foo: "bar"
};

const currentFilePathSample = "./src/sub/a.js";

function replaceImportPathAliases(currentFilePath, fileContent, pathMap) {
  const regex = createRegex(pathMap);
  return fileContent.replace(regex, replacer);

  function replacer(_, g1, aliasGrp, restPathGrp, g4) {
    const mappedImportPath = pathMap[aliasGrp] + restPathGrp;

    let mappedImportPathRelative = path.posix.relative(
      path.dirname(currentFilePath),
      mappedImportPath
    );
    // append "./" to make it a relative import path
    if (!mappedImportPathRelative.startsWith("../")) {
      mappedImportPathRelative = `./${mappedImportPathRelative}`;
    }
    return g1 + mappedImportPathRelative + g4;
  }
}

function createRegex(pathMap) {
  const mapKeysStr = Object.keys(pathMap).reduce((acc, cur) => `${acc}|${cur}`);
  const regexStr = `^(import.*from\s+["|'])(${mapKeysStr})(.*)(["|'])$`;
  return new RegExp(regexStr, "gm");
}

console.log(
  replaceImportPathAliases(
    currentFilePathSample,
    fileContentSample,
    pathMappingSample
  )
);

我创建了一个脚本来执行此操作。

它基本上遍历项目树,搜索所有文件,使用正则表达式 /"@(\/\w+[\w\/.]+)"/gi 找到看起来像“@/my/import”的导入,然后使用 nodejs 的 path 模块创建相对路径。

我希望你没有任何我没有在这个简单的脚本中涵盖的边缘情况,所以最好备份你的文件。我只在简单的场景下测试过。

这里是 code:

const path = require("path");
const args = process.argv;

const rootName = args[2];
const rootPath = path.resolve(process.cwd(), rootName);
const alias = "@";

if (!rootPath || !alias) return;

const { promisify } = require("util");
const fs = require("fs");

const readFileAsync = promisify(fs.readFile);
const readDirAsync = promisify(fs.readdir);
const writeFileAsync = promisify(fs.writeFile);
const statsAsync = promisify(fs.stat);

function testForAliasImport(file) {
  if (!file.content) return file;

  const regex = /"@(\/\w+[\w\/.]+)"/gi;

  let match,
    search = file.content;

  while ((match = regex.exec(search))) {
    const matchString = match[0];
    console.log(`found alias import ${matchString} in ${file.filepath}`);
    file.content = file.content.replace(
      matchString,
      aliasToRelative(file, matchString)
    );
    search = search.substring(match.index + matchString.length);
  }

  return file;
}

function aliasToRelative(file, importString) {
  let importPath = importString
    .replace(alias, "")
    .split('"')
    .join("");
  const hasExtension = !!path.parse(importString).ext;

  if (!hasExtension) {
    importPath += ".ext";
  }

  const filepath = file.filepath
    .replace(rootPath, "")
    .split("\")
    .join("/");

  let relativeImport = path.posix.relative(path.dirname(filepath), importPath);

  if (!hasExtension) {
    relativeImport = relativeImport.replace(".ext", "");
  }

  if (!relativeImport.startsWith("../")) {
    relativeImport = "./" + relativeImport;
  }

  relativeImport = `"${relativeImport}"`;

  console.log(`replaced alias import ${importString} with ${relativeImport}`);
  return relativeImport;
}

async function writeFile(file) {
  if (!file || !file.content || !file.filepath) return file;
  try {
    console.log(`writing new contents to file ${file.filepath}...`);
    await writeFileAsync(file.filepath, file.content);
  } catch (e) {
    console.error(e);
  }
}

async function prepareFile(filepath) {
  const stat = await statsAsync(filepath);
  return { stat, filepath };
}

async function processFile(file) {
  if (file.stat.isFile()) {
    console.log(`reading file ${file.filepath}...`);
    file.content = await readFileAsync(file.filepath);
    file.content = file.content.toString();
  } else if (file.stat.isDirectory()) {
    console.log(`traversing dir ${file.filepath}...`);
    await traverseDir(file.filepath);
  }
  return file;
}

async function traverseDir(dirPath) {
  try {
    const filenames = await readDirAsync(dirPath);
    const filepaths = filenames.map(name => path.join(dirPath, name));
    const fileStats = await Promise.all(filepaths.map(prepareFile));
    const files = await Promise.all(fileStats.map(processFile));
    await Promise.all(files.map(testForAliasImport).map(writeFile));
  } catch (e) {
    console.error(e);
  }
}


traverseDir(rootPath)
  .then(() => console.log("done"))
  .catch(console.error);

请务必提供目录名称作为参数。例如 src

对于 IDE 部分,我知道 Jetbrains Webstorm 允许您定义 npm 任务。
创建一个 scripts 目录来保存脚本。
package.json

中定义脚本
"scripts": {
    ...
    "replaceimports": "node scripts/script.js \"src\""
}

注册 npm 任务以在 npm 工具中使用 window。

一种显着减少花在任务上的时间的简单方法是使用正则表达式模式匹配仅定位位于特定深度级别的文件。假设你有一个指向你的 components 文件夹的魔法路径和一个像这样的项目结构:

...
├── package.json
└── src
    └── components

您可以通过简单的查找和替换来重构它:

find: from "components
replace: from "../components
files to include: ./src/*/**.ts

然后你就递归地去:

find: from "components
replace: from "../../components
files to include: ./src/*/*/**.ts

我写了一篇关于这个的小博客post:https://dev.to/fes300/refactoring-absolute-paths-to-relative-ones-in-vscode-3iaj