ts的host.writeFile()第一个参数路径的分隔符为什么和我的系统不匹配?-灵析社区

全能人才

在看ms库的源码 这里build.js文件中自定义了host.writeFile方法 function compile(files, options) { const compilerOptions = { ...config.compilerOptions, ...options }; const host = ts.createCompilerHost(compilerOptions); host.writeFile = (fileName, contents) => { const isDts = fileName.endsWith('.d.ts'); console.log(fileName.split(sep),sep) //[ 'src/index.js' ] \ let path = join(DIR, fileName.split(sep)[1]); 注意看我上面的打印结果 我是win11系统,sep返回值是正确的,但是fileName传入的是src/index.js 这里是ts内部写死了这个分隔符吗? 这种情况下,我运行这个文件会直接报错,因为`fileName.split('sep')[1]`拿到的是undefined 当我修改成 let path = join(DIR, fileName.split('/')[1]); 是可以正常运行的 源码位置 [https://github.com/vercel/ms/blob/master/scripts/build.js](https://link.segmentfault.com/?enc=ScNswQf7C2w7RC11XUxyrQ%3D%3D.zdfpVaMrLMlDycC%2FJRYQALNRbvLWqbkd6DUd0iSFmeRXpqlJQzd94WWVOy%2BVrrJiXEYTGNVnXw5bwvKU27%2Bylg%3D%3D)

阅读量:32

点赞量:0

问AI
可能是兼容问题,用Node.js的path模块,path模块可以根据运行环境自动选对的分隔符: const path = require('path'); function compile(files, options) { const compilerOptions = { ...config.compilerOptions, ...options }; const host = ts.createCompilerHost(compilerOptions); host.writeFile = (fileName, contents) => { const isDts = fileName.endsWith('.d.ts'); const normalizedFileName = path.normalize(fileName); // 用 path.join 来构建路径,会自动处理路径分隔符 let outputPath = path.join(DIR, normalizedFileName); // 进行文件写入等操作 // ... }; // ... }