Skip to content

Instantly share code, notes, and snippets.

@TotooriaHyperion
Created April 6, 2020 08:11
Show Gist options
  • Save TotooriaHyperion/13f7f50aa413f744bba7bddc860c4c12 to your computer and use it in GitHub Desktop.
Save TotooriaHyperion/13f7f50aa413f744bba7bddc860c4c12 to your computer and use it in GitHub Desktop.
using FriendlyErrorsWebpackPlugin with ForkTsChecker
import * as webpack from "webpack";
import * as ForkTsChecker from "fork-ts-checker-webpack-plugin";
import * as FriendlyError from "friendly-errors-webpack-plugin";
import { debounce } from "lodash";
const forkTsStack: Array<{
type: "info" | "error" | "warn";
message: string;
}> = [];
// 1.create a simple signal of webpack's latest compile behavior.
let webpackCompilePromise: Promise<any>;
let webpackCompilePromiseResolve: any;
const updateWebpackCompilePromise = () => {
forkTsStack.length = 0;
webpackCompilePromise = new Promise((resolve) => {
webpackCompilePromiseResolve = resolve;
});
};
// 2.use lodash.debounc to group sync output, and output them after the latest webpack compile complete.
const forkTsLogDebounce = debounce(() => {
if (!webpackCompilePromise) {
return;
}
webpackCompilePromise.then(() => {
forkTsStack.forEach((item) => {
if (item.type === "info") {
console.info(item.message);
}
if (item.type === "error") {
console.error(item.message);
}
if (item.type === "warn") {
console.warn(item.message);
}
});
});
}, 100);
// 3.delay forkTsChecker logger and save them into a stack for later use
const forkTsDelayLogger: ForkTsChecker.Logger = {
info: (message) => {
forkTsStack.push({
type: "info",
message,
});
forkTsLogDebounce();
},
error: (message) => {
forkTsStack.push({
type: "error",
message,
});
forkTsLogDebounce();
},
warn: (message) => {
forkTsStack.push({
type: "warn",
message,
});
forkTsLogDebounce();
},
};
const webpackConfig: webpack.Configuration = {
plugins: [
new FriendlyError(),
new ForkTsChecker({
logger: forkTsDelayLogger,
}),
],
};
// 4.create webpack compiler
const compiler = webpack(webpackConfig);
updateWebpackCompilePromise();
const doneFn = () => {
if (webpackCompilePromiseResolve) {
webpackCompilePromiseResolve();
}
};
const invalidFn = () => {
updateWebpackCompilePromise();
};
// 5.listen to compile hook
if (compiler.hooks) {
compiler.hooks.done.tap("HyperionCli", doneFn);
compiler.hooks.invalid.tap("HyperionCli", invalidFn);
compiler.hooks.compile.tap("HyperionCli", updateWebpackCompilePromise);
} else {
compiler.plugin("done", doneFn);
compiler.plugin("invalid", invalidFn);
compiler.plugin("compile", updateWebpackCompilePromise);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment