以前にGulpとwebpackとTypeScriptで開発環境を作成する記事を投稿しましたが、webpack-streamとgulp.watchを使用時にエラーが出ると監視が止まってしまうことがあったので、対応方法をメモしておきます。
対応前
対応前のgulpfile.jsです。
const gulp = require('gulp');
const webpackStream = require('webpack-stream');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config.js');
gulp.task('webpack', function() {
return webpackStream(webpackConfig, webpack)
.pipe(gulp.dest('dist'));
});
gulp.task('watch', function() {
gulp.watch('./src/js/**/*.ts', gulp.task('webpack'));
});
main.tsをエラーが出るように修正します。
import {hello} from './greeting';
let message: string;
message = hello('Miku');
alert(message);
message = 123;
watchのタスクを実行した状態で保存すると、以下のようにエラーが出て監視が止まってしまいました。
(node:28751) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:28751) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
対応方法1
webpackの設定で .on(‘error’, function) を追加するといいようです。
const gulp = require('gulp');
const webpackStream = require('webpack-stream');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config.js');
gulp.task('webpack', function() {
return webpackStream(webpackConfig, webpack).on('error', function (e) {
this.emit('end');
})
.pipe(gulp.dest("dist"));
});
gulp.task('watch', function() {
gulp.watch('./src/js/**/*.ts', gulp.task('webpack'));
});
これできちんとエラーが出て監視も続くようになりました。
ERROR in /XXXXX/src/js/main.ts
[tsl] ERROR in /XXXXX/src/js/main.ts(7,1)
TS2322: Type 'number' is not assignable to type 'string'.
webpack 5.5.1 compiled with 1 error
対応方法2
今回の場合出力先はwebpack.config.jsで設定しているので、.pipe(gulp.dest()) を削除する形でも解消されるようでした。
const gulp = require('gulp');
const webpackStream = require('webpack-stream');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config.js');
gulp.task('webpack', function() {
return webpackStream(webpackConfig, webpack);
});
gulp.task('watch', function() {
gulp.watch('./src/js/**/*.ts', gulp.task('webpack'));
});
この場合も先ほどと同様に、きちんとエラーが出て監視も続く状態になりました。
ERROR in /XXXXX/src/js/main.ts
[tsl] ERROR in /XXXXX/src/js/main.ts(7,1)
TS2322: Type 'number' is not assignable to type 'string'.
webpack 5.5.1 compiled with 1 error
コメントが承認されるまで時間がかかります。