Docker化TypeScript Node.js应用运行报错:未知.ts扩展名问题
TypeScript Node.js Docker化报错:未知文件扩展名.ts问题解决
问题现象
执行docker-compose build && docker-compose up -d启动应用时,出现错误:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /src/src/app.ts
相关配置文件
Dockerfile
# Download the slim version of node FROM node:21-slim # Set the work directory to app folder. # We will be copying our code here WORKDIR /src #Copy package.json file in the node folder inside container COPY package.json . # Copy the rest of the code in the container COPY . . # Install the dependencies in the container RUN npm install # Run the node server with server.js file CMD ["npm", "start"] # Expose the service over PORT 5000 EXPOSE 5000
package.json 启动脚本
"scripts": { "start": "nodemon -w src --ext ts --exec ts-node --esm src/app.ts" },
docker-compose.yml
version: '3.8' services: node_app: build: ./node container_name: node environment: - NODE_ENV=development - PORT=5000 command: sh -c "npm start" volumes: - ./node:/home/node/app:cached ports: - '5000:5000'
项目文件结构:本地代码存放在./node目录下,内部包含src/app.ts等TypeScript源码文件。
解决步骤
1. 修正容器内路径不匹配问题
Dockerfile设置的工作目录是/src,但docker-compose的卷挂载将本地./node映射到了容器的/home/node/app,导致代码同时存在于两个目录,启动命令访问的/src/src/app.ts并非挂载的开发代码目录。
修改Dockerfile的工作目录,与卷挂载路径对齐:
# 替换原WORKDIR行 WORKDIR /home/node/app
2. 适配ESM模式配置
启动命令使用了--esm,需要确保项目配置支持ESM规范:
- 在
package.json中添加:"type": "module" - 在
tsconfig.json中配置TypeScript编译选项:{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "target": "ESNext", "esModuleInterop": true } }
3. 优化启动命令(可选)
若仍有扩展名识别问题,可在启动命令中添加实验性解析器参数:
"scripts": { "start": "nodemon -w src --ext ts --exec 'ts-node --esm --experimental-specifier-resolution=node src/app.ts'" },
4. 清理冗余配置
Dockerfile中已经定义了CMD ["npm", "start"],可移除docker-compose.yml中的command: sh -c "npm start",避免命令冲突。
内容的提问来源于stack exchange,提问作者Sourouche
相关产品推荐
相关产品推荐

