0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

npm run build のあとにバッチファイルが止まる問題の対処法【Windows】

Posted at

概要

VueやReactなどのフロントエンドプロジェクトを Windows のバッチファイル(.bat)でビルド → S3 アップロード → CloudFront 無効化という流れで自動化しようとしたところ、npm run build の後で処理が止まる問題に直面した。

問題

以下のような deploy.bat を実行すると、npm run build は実行されるが、その後の aws s3 syncCloudFront 無効化処理に進まない。

@echo off

set S3_BUCKET=example-bucket
set DISTRIBUTION_ID=EXXXXXXXX

echo Building project...
npm run build

echo Uploading to S3...
aws s3 sync dist/ s3://%S3_BUCKET% --delete

echo Invalidating CloudFront cache...
aws cloudfront create-invalidation --distribution-id %DISTRIBUTION_ID% --paths "/*"

npm run build の出力は正常に完了しているように見えるが、その後の echo が表示されず、バッチファイルが途中で終了してしまう。

原因

Windows のバッチファイルでは、外部プログラム(特に npm script)を呼び出したとき、戻り先がなくなる場合がある。

具体的には、npm run build のように直接実行すると、npm プロセスに制御が渡ったまま、バッチファイルが終了してしまう。

解決策

npm run build の前に call を付ける。

call npm run build

これにより、npm の実行が終わったあと、バッチファイルの続きの処理に制御が戻るようになる。

修正後の例

@echo off

set S3_BUCKET=example-bucket
set DISTRIBUTION_ID=EXXXXXXXX

echo Building project...
call npm run build

echo Uploading to S3...
aws s3 sync dist/ s3://%S3_BUCKET% --delete

echo Invalidating CloudFront cache...
aws cloudfront create-invalidation --distribution-id %DISTRIBUTION_ID% --paths "/*"

echo Deployment completed.
pause

補足:文字コードにも注意

deploy.batUTF-8 BOM付き で保存していると、先頭の @echo off が無視されたり、処理がうまく実行されないこともある。

保存形式は「ANSI」または「UTF-8 (BOMなし)」がおすすめ。


まとめ

Windows バッチで npm run build を使うときは call を付ける。シンプルだけどハマりやすい罠なので、備忘録として記録。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?