TypeScript编译为JavaScript后如何保持资源访问路径正确?
解决ES模块下TypeScript编译后文件路径访问问题
问题背景
当前目录结构:
Node (根目录) -data -123.mp4 -src -test.ts -build -test.js
编译后的build/test.js使用../data/123.mp4会触发“文件或目录不存在”错误,原因有两点:
- 相对路径的解析基于Node执行时的工作目录,而非JS文件所在的
build目录; - ES模块规范中无法直接使用
__dirname这类CommonJS变量。
解决方案
方法1:利用import.meta.url构造绝对路径(推荐)
在src/test.ts中修改代码,通过import.meta.url结合path模块生成稳定的绝对路径:
import { createReadStream, createWriteStream } from 'fs'; import { dirname, join } from 'path'; import { fileURLToPath } from 'url'; // 模拟ES模块环境下的__dirname const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); // 基于当前文件路径,构造指向根目录data文件夹的绝对路径 const inputPath = join(__dirname, '../../data/123.mp4'); const outputPath = join(__dirname, '../../data/copy.mp4'); const readStream = createReadStream(inputPath); const writeStream = createWriteStream(outputPath);
编译后的JS文件会保留路径计算逻辑,无论在哪个目录执行Node命令,都能精准定位到目标文件。
方法2:固定执行时的工作目录
如果不想修改代码,可直接在项目根目录下执行编译后的文件:
node build/test.js
此时../data/123.mp4的相对路径会基于根目录解析,能正确找到文件。但这种方式依赖执行时的工作目录,灵活性较差。
方法3:使用TypeScript路径别名(适合大型项目)
通过tsconfig.json配置路径别名,配合工具转译,简化路径写法:
- 修改
tsconfig.json的compilerOptions:
{ "compilerOptions": { // ...原有配置 "baseUrl": ".", "paths": { "@data/*": ["data/*"] } } }
- 在
src/test.ts中结合import.meta.url使用别名(需配合tsconfig-paths等工具完成转译):
import { createReadStream, createWriteStream } from 'fs'; import { join } from 'path'; import { fileURLToPath } from 'url'; import 'tsconfig-paths/register'; const inputPath = join(fileURLToPath(import.meta.url), '../../../data/123.mp4'); // 或通过工具转译@data/123.mp4为绝对路径
内容的提问来源于stack exchange,提问作者GodAmongUs
相关产品推荐
相关产品推荐

