From deb937498907b84a13de4eddd50db587259f0d08 Mon Sep 17 00:00:00 2001 From: Jess Archer Date: Sun, 3 Jul 2022 11:43:23 +1000 Subject: [PATCH] Help users that visit the Vite dev server directly --- package.json | 2 +- src/dev-server-index.html | 20 ++++++++++++++++++++ src/index.ts | 23 ++++++++++++++++++++--- 3 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 src/dev-server-index.html diff --git a/package.json b/package.json index e51a39b..aa5e725 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ ], "scripts": { "build": "npm run build-plugin && npm run build-inertia-helpers", - "build-plugin": "rm -rf dist && tsc", + "build-plugin": "rm -rf dist && tsc && cp src/dev-server-index.html dist/", "build-inertia-helpers": "rm -rf inertia-helpers && tsc --project tsconfig.inertia-helpers.json", "lint": "eslint --ext .ts ./src ./tests", "ssr:serve": "vite build --ssr && node storage/ssr/ssr.js", diff --git a/src/dev-server-index.html b/src/dev-server-index.html new file mode 100644 index 0000000..53ea994 --- /dev/null +++ b/src/dev-server-index.html @@ -0,0 +1,20 @@ + + + + + + Laravel Vite + + + + + + + +

The Vite server should not be accessed directly. Please visit {{ url }} instead

+ + diff --git a/src/index.ts b/src/index.ts index cbe2f5a..d34ac81 100644 --- a/src/index.ts +++ b/src/index.ts @@ -164,6 +164,9 @@ function resolveLaravelPlugin(pluginConfig: Required): LaravelPlug configureServer(server) { const hotFile = path.join(pluginConfig.publicDirectory, 'hot') + const envDir = resolvedConfig.envDir || process.cwd() + const appUrl = loadEnv('', envDir, 'APP_URL').APP_URL + server.httpServer?.once('listening', () => { const address = server.httpServer?.address() @@ -177,9 +180,6 @@ function resolveLaravelPlugin(pluginConfig: Required): LaravelPlug viteDevServerUrl = `${protocol}://${host}:${address.port}` fs.writeFileSync(hotFile, viteDevServerUrl) - const envDir = resolvedConfig.envDir || process.cwd() - const appUrl = loadEnv('', envDir, 'APP_URL').APP_URL - setTimeout(() => { server.config.logger.info(colors.red(`\n Laravel ${laravelVersion()} `)) server.config.logger.info(`\n > APP_URL: ` + colors.cyan(appUrl)) @@ -203,6 +203,23 @@ function resolveLaravelPlugin(pluginConfig: Required): LaravelPlug process.on('SIGHUP', process.exit) exitHandlersBound = true + + return () => { + server.middlewares.use((req, res, next) => { + if (req.url === '/index.html') { + server.config.logger.warn( + "\n" + colors.bgYellow( + colors.black(`The Vite server should not be accessed directly. Please visit ${appUrl} instead.`) + ) + ) + res.end( + fs.readFileSync(path.join(__dirname, 'dev-server-index.html')).toString().replace(/{{ url }}/g, appUrl) + ) + } + + next() + }); + } }, // The following two hooks are a workaround to help solve a "flash of unstyled content" with Blade.