将Typescript绝对路径转换为Node.js相对路径?

我正在将打字稿编译为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在根distdist/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()语句生成正确的相对路径

似乎这可能是一个相当普遍的模式,因此请避免重新发明轮子...

我已经实现了一个脚本,可以为我的项目解决此问题我们的目标是能够使用非相对路径(我们可以使用Typescriptspaths配置选项进行此操作),并使已编译的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);
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章