前提
環境構築の勉強過程中です。
TypeScriptとNode.jsのExpressをDockerを活用して
サーバーを立ち上げたいです。
実現したいこと
前提に記載した通り
「TypeScriptとNode.jsのExpressをDockerを活用してサーバーを立ち上げたい」
ですが。
目に見えるゴールとしてはこの後記載します「index.ts」内の「こんにちは」
を表示させたいです。
発生している問題・エラーメッセージ
コンテナは作成できたのですが、いざコンテナを起動してみると
一瞬だけ起動しすぐ停止してしまいます。
Docker上のログをみると下記のように出力されていました。
エラーメッセージ yarn run v1.22.19 $ node ./index.ts /bff/index.ts:1 import express from 'express' ^^^^^^ SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:74:18) at wrapSafe (node:internal/modules/cjs/loader:1141:20) at Module._compile (node:internal/modules/cjs/loader:1182:27) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 Node.js v18.13.0 error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
該当のソースコード
tsconfig.json
1{ 2 "include": [ 3 // コンパイルするファイルを指定する。 4 "index.ts", 5 ], 6 "compilerOptions": { 7 // コンパイルする際のオプションを書いていく。 8 "target": "es2016", 9 "module": "commonjs", 10 }, 11}
index.ts
1import express from 'express' 2const app: express.Express = express() 3app.get("/", (req:express.Request, res:express.Response)=>{ 4 res.send("こんにちは"); 5}) 6app.listen(3000,()=>{ 7 console.log('ポート3000番で起動しました。') 8})
package.json
1{ 2 "name": "bff", 3 "version": "1.0.0", 4 "description": "", 5 "main": "index.js", 6 "scripts": { 7 "start": "nodemon ./index.ts", 8 "dev": "node ./index.ts", 9 "test": "echo \"Error: no test specified\" && exit 1" 10 }, 11 "keywords": [], 12 "author": "", 13 "license": "ISC", 14 "devDependencies": { 15 "@types/express": "^4.17.15", 16 "@types/node": "^18.11.18", 17 "nodemon": "^2.0.20", 18 "ts-node": "^10.9.1", 19 "typescript": "^4.9.4" 20 }, 21 "dependencies": { 22 "express": "^4.18.2" 23 } 24}
Docker
1FROM node:18-alpine 2 3WORKDIR /bff 4 5COPY . . 6 7CMD ["yarn", "start"] 8
試したこと
package.jsonに「"type": "module" 」を入れてみましたがダメでした…(下記その際のエラー)
エラーメッセージ node:internal/errors:491 ErrorCaptureStackTrace(err); ^ TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /bff/index.ts
調べると大抵はtarget、moduleの値(文法ルール)を変えたらうまくいくケースがほとんどでしたが
どれもうまくいかず同じように「import」の箇所でエラーが出ていました。
どなたか解決策をご教示お願いいたします。
何卒よろしくお願いいたします。
補足情報(FW/ツールのバージョンなど)
Node.js v18.13.0
Docker v4.13.1
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。