gpt4 book ai didi

javascript - 将 Typescript 绝对路径转换为 ​​NodeJS 相对路径?

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:15 28 4
gpt4 key购买 nike

我正在将 typescript 编译为 es5/commonjs 格式。我使用 typescript 的 tsconfig.json paths 属性为“import 语句”指定固定根。

例如,我可能有一个路径配置@example: './src/'

编译 *.ts 文件后,require 语句将类似于:

require('@example/boo/foo');

我需要创建一个后处理脚本,该脚本考虑当前 javascript 文件的路径和导入路径。

因此,例如,如果导入更新的 javascript 文件位于 dist/foo/pitythefoo.js 中,并且它从 dist/boo/boo.js 导入导出,则路径 @example/boo/boo 必须替换为 ../boo/boo

现在,如果 pitythefoo.js 位于 dist 的根目录(dist/pitythefoo.js,则 @example 字符串将被替换为 ./

所以基本算法似乎是:

如果文件位于 dist 的根目录,则将 @example 替换为 ./。如果更深,则计算深度,如果是两个目录深,则添加 ../.. 以向上移动到根目录,然后移动到导入模块资源所在的路径。听起来合理吗?

所以总的来说,我在想这样的事情:

globby('dist/**/*.js'). //get the paths of all the js files
then(process); //read each file as a text file and perform the string replacement
//Save the file using the original file name.


function process(path:string) {
const file = fs.readFileSync(path);
//update require statements contents of file
fs.writeFileSync(file,path);
}

有人知道有一个实用程序可以分析导入路径长度和当前资源的路径并为 require() 语句生成正确的相对路径吗?

这似乎是一种相当常见的模式,因此尽量避免重新发明轮子......

最佳答案

I've implemented a script that solves this for my project 。目标是能够使用非相对路径,我们可以使用 Typescripts paths 配置选项来实现这一点,并让编译后的 ES5/CommonJS 输出使用相对路径,以便可以将包发布到 NPM。上面的链接有github版本,这里是代码:

    const fs = require("fs");
const globby = require("globby");
require("mkdirp").sync("dist");
require("cpy")("package.json", "dist");
const options = { overwrite: true };
const rc = require("recursive-copy");
rc("target/src/", "dist", options).then(() => {
globby("./dist/**/*.js")
.then(paths => {
paths.forEach(update);
})
.catch(e => console.log(e));

globby("./dist/**/*.d.ts")
.then(paths => {
paths.forEach(update);
})
.catch(e => console.log(e));
});

function update(path) {
count = (path.match(/\//g) || []).length;
let replacement = "";
if (count == 2) {
replacement = "./";
} else if (count > 2) {
const size = count - 2;
replacement = Array(size)
.fill("../")
.join("");
} else {
throw new Error("Invalid / count in path of file");
}
let js = fs.readFileSync(path, "utf8");
js = js.replace(/@fs\//g, replacement);
fs.writeFileSync(path, js);
}

关于javascript - 将 Typescript 绝对路径转换为 ​​NodeJS 相对路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51372018/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com