From 00fcab2ebf25f65c8500963e40a5ac617b32f426 Mon Sep 17 00:00:00 2001 From: cyly <786156072@qq.com> Date: Sun, 26 Jun 2022 21:33:45 +0800 Subject: [PATCH] fix: compiler.watcher undefined (#434) * fix: compiler.watcher undefined * docs: add comment --- src/core/unplugin.ts | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/core/unplugin.ts b/src/core/unplugin.ts index b9f78319..922e9449 100644 --- a/src/core/unplugin.ts +++ b/src/core/unplugin.ts @@ -2,10 +2,13 @@ import { createUnplugin } from 'unplugin' import { createFilter } from '@rollup/pluginutils' import chokidar from 'chokidar' import type { ResolvedConfig, ViteDevServer } from 'vite' +import type { Watching } from 'webpack' import type { Options, PublicPluginAPI } from '../types' import { Context } from './context' import { shouldTransform, stringifyComponentImport } from './utils' +const PLUGIN_NAME = 'unplugin:webpack' + export default createUnplugin((options = {}) => { const filter = createFilter( options.include || [/\.vue$/, /\.vue\?vue/], @@ -67,16 +70,22 @@ export default createUnplugin((options = {}) => { }, webpack(compiler) { - if (compiler.options.mode !== 'development') - return + let watcher: Watching let fileDepQueue: { path: string; type: 'unlink' | 'add' }[] = [] - ctx.setupWatcherWebpack(chokidar.watch(ctx.options.globs), (path: string, type: 'unlink' | 'add') => { - fileDepQueue.push({ path, type }) - process.nextTick(() => { - compiler.watching.invalidate() - }) + compiler.hooks.watchRun.tap(PLUGIN_NAME, () => { + // ensure watcher is ready(supported since webpack@5.0.0-rc.1) + if (!watcher && compiler.watching) { + watcher = compiler.watching + ctx.setupWatcherWebpack(chokidar.watch(ctx.options.globs), (path: string, type: 'unlink' | 'add') => { + fileDepQueue.push({ path, type }) + // process.nextTick is for aggregated file change event + process.nextTick(() => { + watcher.invalidate() + }) + }) + } }) - compiler.hooks.compilation.tap('unplugin-vue-components', (compilation) => { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { if (fileDepQueue.length) { fileDepQueue.forEach(({ path, type }) => { if (type === 'unlink')