【问题标题】:Converting Typescript absolute paths to nodejs relative paths?将 Typescript 绝对路径转换为 ​​nodejs 相对路径?
【发布时间】:2018-12-24 14:28:20
【问题描述】:

我正在将 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.jsdist 的根(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() 语句生成正确相对路径的实用程序?

这似乎是一个相当普遍的模式,所以尽量避免重新发明轮子......

【问题讨论】:

    标签: javascript node.js typescript npm commonjs


    【解决方案1】:

    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);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-12-14
      • 2017-08-01
      • 2011-11-07
      • 2011-05-02
      相关资源
      最近更新 更多