From 963c38b13e4347ffc33f88b63ebc779138ec98da Mon Sep 17 00:00:00 2001 From: Maximo Mussini Date: Thu, 16 Mar 2023 16:52:07 -0300 Subject: [PATCH] feat: help users that visit the vite dev server directly Based on https://github.com/laravel/vite-plugin/pull/57, thanks @jessarcher!! --- vite-plugin-ruby/src/dev-server-index.html | 66 ++++++++++++++++++++++ vite-plugin-ruby/src/index.ts | 13 ++++- vite-plugin-ruby/tsup.config.ts | 5 ++ 3 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 vite-plugin-ruby/src/dev-server-index.html diff --git a/vite-plugin-ruby/src/dev-server-index.html b/vite-plugin-ruby/src/dev-server-index.html new file mode 100644 index 00000000..31dbf4c2 --- /dev/null +++ b/vite-plugin-ruby/src/dev-server-index.html @@ -0,0 +1,66 @@ + + + + + + Vite Ruby + + + + + + + + + + +
+
+
+ +
+
+

This is the Vite development server that provides Hot Module Replacement for your Ruby application.

+

To access your Ruby application, you will need to run a local development server.

+

The Rails Command Line

+

Start the Rails server by running: bin/rails s

+
+
+

Want more information on Vite Ruby's Rails integration?

+

+ Read the docs → +

+
+
+
+
+
+ + diff --git a/vite-plugin-ruby/src/index.ts b/vite-plugin-ruby/src/index.ts index 0bd2fe7c..b24e4ab8 100644 --- a/vite-plugin-ruby/src/index.ts +++ b/vite-plugin-ruby/src/index.ts @@ -1,4 +1,5 @@ -import { basename, posix } from 'path' +import { basename, posix, resolve } from 'path' +import { existsSync, readFileSync } from 'fs' import type { ConfigEnv, PluginOption, UserConfig, ViteDevServer } from 'vite' import createDebugger from 'debug' @@ -74,6 +75,16 @@ function config (userConfig: UserConfig, env: ConfigEnv): UserConfig { // Internal: Allows to watch additional paths outside the source code dir. function configureServer (server: ViteDevServer) { server.watcher.add(watchAdditionalPaths) + + return () => server.middlewares.use((req, res, next) => { + if (req.url === '/index.html' && !existsSync(resolve(server.config.root, 'index.html'))) { + res.statusCode = 404 + const file = readFileSync(resolve(__dirname, 'dev-server-index.html'), 'utf-8') + res.end(file) + } + + next() + }) } function outputOptions (assetsDir: string, ssrBuild: boolean) { diff --git a/vite-plugin-ruby/tsup.config.ts b/vite-plugin-ruby/tsup.config.ts index 5f783421..4309b52c 100644 --- a/vite-plugin-ruby/tsup.config.ts +++ b/vite-plugin-ruby/tsup.config.ts @@ -1,4 +1,6 @@ +import { copyFileSync } from 'fs' import type { Options } from 'tsup' + export const tsup: Options = { clean: true, dts: true, @@ -6,4 +8,7 @@ export const tsup: Options = { sourcemap: true, target: 'node12', format: ['esm', 'cjs'], + async onSuccess () { + copyFileSync('src/dev-server-index.html', 'dist/dev-server-index.html') + }, }