From 66725b86e401b26dd78b0f2cecf6a61d75567637 Mon Sep 17 00:00:00 2001 From: Alex MacArthur Date: Thu, 10 Nov 2022 22:51:39 -0600 Subject: [PATCH] Add support for mounting script when body does not exist. --- README.md | 2 +- package.json | 2 +- src/steps.test.ts | 28 +++++++++++++++++++++++++++- src/steps.ts | 7 ++++++- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f818082..7ab8570 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ export default defineConfig({ }); ``` -At the very least, you'll need to specify a remote page you'd like to proxy, as well as which local entry point Vite should inject onto the page. +At the very least, you'll need to specify a remote page you'd like to proxy, as well as which local entry point Vite should inject onto the page. By default, this script tag will be injected just before the closing `` tag, but if that doesn't exist, it'll be attached to the end of the HTML. ```diff // vite.config.js diff --git a/package.json b/package.json index 1eb3841..d06b8cb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "vite-plugin-proxy-page", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "author": "Alex MacArthur (https://macarthur.me)", "homepage": "https://macarthur.me/posts/project-local-spa-onto-production-page", diff --git a/src/steps.test.ts b/src/steps.test.ts index dab4282..e990781 100644 --- a/src/steps.test.ts +++ b/src/steps.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vitest"; -import { remoteRemoteEntryPoint, setUpRootElement } from "./steps"; +import { + insertLocalEntryScript, + remoteRemoteEntryPoint, + setUpRootElement, +} from "./steps"; import { htmlMatches } from "./test-utils"; describe("setUpRootElement()", () => { @@ -114,3 +118,25 @@ describe("remoteRemoteEntryPoint()", () => { expect(patternResult).toEqual(html); }); }); + +describe("insertLocalEntryScript()", () => { + it("mounts script to inside of body if body element exists", () => { + const html = `
hello
`; + + const result = insertLocalEntryScript(html, "./my-script.js"); + + expect(result).toEqual( + '
hello
' + ); + }); + + it("mounts script outside all HTML if body element does not exist", () => { + const html = `
hello
`; + + const result = insertLocalEntryScript(html, "./my-script.js"); + + expect(result).toEqual( + '
hello
' + ); + }); +}); diff --git a/src/steps.ts b/src/steps.ts index bae1456..af60854 100644 --- a/src/steps.ts +++ b/src/steps.ts @@ -57,7 +57,12 @@ export function insertLocalEntryScript( localEntryPoint: string ): string { const constructedScript = ``; - return html.replace(/(<\/body>)/, `${constructedScript}$1`); + + if (/<\/body>/.test(html)) { + return html.replace(/(<\/body>)/, `${constructedScript}$1`); + } + + return `${html}${constructedScript}`; } const sourcesPattern = /(<[^<].*?(?:src|href)=(?:"|'))(.+?)((?:"|').*?>)/g;