summaryrefslogtreecommitdiff
path: root/packages/astro/src/vite-plugin-load-fallback/index.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/astro/src/vite-plugin-load-fallback/index.ts')
-rw-r--r--packages/astro/src/vite-plugin-load-fallback/index.ts38
1 files changed, 38 insertions, 0 deletions
diff --git a/packages/astro/src/vite-plugin-load-fallback/index.ts b/packages/astro/src/vite-plugin-load-fallback/index.ts
new file mode 100644
index 000000000..6a6af9142
--- /dev/null
+++ b/packages/astro/src/vite-plugin-load-fallback/index.ts
@@ -0,0 +1,38 @@
+import type * as vite from 'vite';
+import nodeFs from 'fs';
+
+type NodeFileSystemModule = typeof nodeFs;
+
+export interface LoadFallbackPluginParams {
+ fs?: NodeFileSystemModule;
+}
+
+export default function loadFallbackPlugin({ fs }: LoadFallbackPluginParams): vite.Plugin | false {
+ // Only add this plugin if a custom fs implementation is provided.
+ if(!fs || fs === nodeFs) {
+ return false;
+ }
+
+ return {
+ name: 'astro:load-fallback',
+ enforce: 'post',
+ async load(id) {
+ try {
+ // await is necessary for the catch
+ return await fs.promises.readFile(cleanUrl(id), 'utf-8')
+ } catch (e) {
+ try {
+ return await fs.promises.readFile(id, 'utf-8');
+ } catch(e2) {
+ // Let fall through to the next
+ }
+ }
+ }
+ }
+}
+
+const queryRE = /\?.*$/s;
+const hashRE = /#.*$/s;
+
+const cleanUrl = (url: string): string =>
+ url.replace(hashRE, '').replace(queryRE, '');