运行我的 dockerized Node 服务器抛出异常:
ERROR: SyntaxError: Cannot use import statement outside a module
我正在使用 typescript ,在我的机器上使用 node dist/index
编译代码后,使用 tsc
从构建文件夹运行编译后的打字稿没有问题。该错误仅在应用程序在 Docker 容器内运行时发生。
编译后的代码在我的本地机器上运行没有问题,但在 Docker 容器内失败,即使 Dockerfile 运行与我手动执行的相同的编译后的 javascript 代码,有什么可能解释?
我的本地 Node 版本:15.12.0
"type": "module"
添加到我的 package.json 会导致错误:Uncaught ReferenceError: exports is not defined
运行编译后的 js 代码时。此打字稿部分在 Docker 容器内作为已编译的 js 代码中断:
import {x} from "../x";
我的 tsconfig.json:
[...]
"target": "esnext",
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
[...]
我的 Dockerfile:
FROM node:15 AS build
WORKDIR /usr/src/app
COPY package*.json ./
COPY src ./src
COPY tsconfig.json ./
RUN npm install
RUN npm run build
FROM build AS run
WORKDIR /usr/src/app
ENV NODE_ENV production
COPY package.json ./
RUN npm install --only=production
COPY --from=0 /usr/src/app/dist .
CMD ["node", "dist/index.js"]
USER node
我的 package.json:
"ts-node": "^9.0.0",
"typescript": "^4.1.3",
[...],
"scripts": {
"build": "tsc"
}
答案 0 :(得分:0)
简单地复制 Dockerfile 中的 dist 文件夹而不是让 docker 容器构建代码本身似乎可以工作。 Docker 不构建 CommonJS 代码肯定是有原因的,即使它在 tsconfig.xml 中指定。将 CommonJS 指定为 tsc
命令的一部分也没有帮助。
这有效,即使它不是最佳的:
FROM node:15 AS build
WORKDIR /usr/src/app
COPY package*.json ./
COPY dist ./dist
COPY ormconfig.json ./ormconfig.json
RUN npm install
CMD ["node", "dist/index.js"]
USER node