Skip to content

Commit

Permalink
refactor: move hook utility into utils/webpack
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Nov 7, 2018
1 parent 52caede commit e279575
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 14 deletions.
18 changes: 5 additions & 13 deletions src/plugin.js
Expand Up @@ -5,7 +5,7 @@ import prettyTime from 'pretty-time';
import { startCase } from './utils';

import * as reporters from './reporters'; // eslint-disable-line import/no-namespace
import { parseRequest } from './utils/request';
import { parseRequest, hook } from './utils/webpack';

// Use bars when possible as default
const isMinimal = env.ci || env.test || !env.tty;
Expand Down Expand Up @@ -127,16 +127,8 @@ export default class WebpackBarPlugin extends ProgressPlugin {
apply(compiler) {
super.apply(compiler);

// Hook helper for webpack 3 + 4 support
function hook(hookName, fn) {
if (compiler.hooks) {
compiler.hooks[hookName].tap('WebpackBar:' + hookName, fn);
} else {
compiler.plugin(hookName, fn);
}
}

hook('afterPlugins', () => {
// Initialize our state before actual build
hook(compiler, 'afterPlugins', () => {
// Keep our state in shared object
if (!this.states[this.options.name]) {
this.states[this.options.name] = {
Expand All @@ -148,7 +140,7 @@ export default class WebpackBarPlugin extends ProgressPlugin {
});

// Hook into the compiler before a new compilation is created.
hook('compile', () => {
hook(compiler, 'compile', () => {
Object.assign(this.state, {
...DEFAULT_STATE,
start: process.hrtime(),
Expand All @@ -158,7 +150,7 @@ export default class WebpackBarPlugin extends ProgressPlugin {
});

// Compilation has completed
hook('done', (stats) => {
hook(compiler, 'done', (stats) => {
const time = prettyTime(process.hrtime(this.state.start), 2);
const hasErrors = stats.hasErrors();
const status = hasErrors ? 'with some errors' : 'succesfuly';
Expand Down
2 changes: 1 addition & 1 deletion src/reporters/fancy.js
Expand Up @@ -3,7 +3,7 @@ import chalk from 'chalk';
import consola from 'consola';

import { renderBar, colorize, ellipsisLeft } from '../utils/cli';
import { formatRequest } from '../utils/request';
import { formatRequest } from '../utils/webpack';
import { BULLET, TICK, CROSS, CIRCLE_OPEN } from '../utils/consts';
import LogUpdate from '../utils/log-update';

Expand Down
9 changes: 9 additions & 0 deletions src/utils/request.js → src/utils/webpack.js
Expand Up @@ -31,3 +31,12 @@ export const formatRequest = (request) => {

return `${loaders}${NEXT}${request.file}`;
};

// Hook helper for webpack 3 + 4 support
export function hook(compiler, hookName, fn) {
if (compiler.hooks) {
compiler.hooks[hookName].tap('WebpackBar:' + hookName, fn);
} else {
compiler.plugin(hookName, fn);
}
}

0 comments on commit e279575

Please sign in to comment.