【发布时间】: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.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() 语句生成正确相对路径的实用程序?
这似乎是一个相当普遍的模式,所以尽量避免重新发明轮子......
【问题讨论】:
标签: javascript node.js typescript npm commonjs