vite-plugin-restart icon indicating copy to clipboard operation
vite-plugin-restart copied to clipboard

Doesn't work with node_modules

Open kewp opened this issue 2 years ago • 2 comments

Not sure why, but this does not work when watching something in node_modules ... Any idea why?

kewp avatar Mar 01 '22 08:03 kewp

@kewp The Vite server watcher skips node_modules/ by default. They have docs on how to enable this, but it still doesn't seem to work for me. handleFileChange is called for "local" changes, but no changes in node_modules. Looking at the source code for this plugin, I don't see anything that would get in the way, but who knows. Would love to get this working!

anicholls avatar Jun 10 '22 23:06 anicholls

After a bit more investigation I think I figured it out! 🎉

Because vite-plugin-restart uses path.posix.join(root, i)) when initializing the restart/reload globs, it appends the config.root to the path passed in. This means any paths passed in can be relative to the project/config root with no issue (normally). It does not check if the path is absolute, so relative paths are required for this plugin's config

I put this relative path in a variable and used it for both ViteRestart and the Vite config mentioned above. This was my mistake. Vite requires the server.watch.ignored path to be absolute.

Working example:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
import ViteRestart from "vite-plugin-restart";

// Change to any package in your node_modules
const myModule = "pick-any-module";
const modulePath = `node_modules/${myModule}/*`;

export default defineConfig({
  plugins: [
    react(),
    ViteRestart({
      reload: [modulePath],
    }),
  ],
  server: {
    watch: {
      ignored: [`!${path.join(process.cwd(), modulePath)}`],
    },
  },
  optimizeDeps: {
    exclude: [myModule],
  },
});

anicholls avatar Jun 15 '22 00:06 anicholls