Fix injected scripts not injected to injected routes (#7262)

* Fix injected scripts not injected to injected routes

* chore: changeset

---------

Co-authored-by: Nate Moore <natemoo-re@users.noreply.github.com>
This commit is contained in:
André Alves 2023-06-06 12:08:38 -03:00 committed by GitHub
parent 67c8f34a99
commit 144813f730
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 56 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fix injected scripts not injected to injected routes

View file

@ -110,6 +110,13 @@ function isInPagesDir(file: URL, config: AstroConfig): boolean {
return file.toString().startsWith(pagesDir.toString());
}
function isInjectedRoute(file: URL, settings: AstroSettings) {
for (const route of settings.injectedRoutes) {
if(file.toString().endsWith(route.entryPoint)) return true;
}
return false;
}
function isPublicRoute(file: URL, config: AstroConfig): boolean {
const pagesDir = resolvePages(config);
const parts = file.toString().replace(pagesDir.toString(), '').split('/').slice(1);
@ -127,7 +134,7 @@ function endsWithPageExt(file: URL, settings: AstroSettings): boolean {
}
export function isPage(file: URL, settings: AstroSettings): boolean {
if (!isInPagesDir(file, settings.config)) return false;
if (!isInPagesDir(file, settings.config) && !isInjectedRoute(file, settings)) return false;
if (!isPublicRoute(file, settings.config)) return false;
return endsWithPageExt(file, settings);
}

View file

@ -1,6 +1,7 @@
import { expect } from 'chai';
import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';
import { tailwind } from './fixtures/astro-scripts/deps.mjs';
describe('Scripts (hoisted and not)', () => {
describe('Build', () => {
@ -139,6 +140,21 @@ describe('Scripts (hoisted and not)', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/astro-scripts/',
integrations: [
tailwind(),
{
name: 'test-script-injection-with-injected-route',
hooks: {
'astro:config:setup': ({ injectRoute, injectScript }) => {
injectScript(
'page',
`import '/src/scripts/something.js';`
);
injectRoute({ pattern: 'injected-route', entryPoint: 'src/external-page.astro' });
},
},
}
],
vite: {
build: {
assetsInlineLimit: 0,
@ -182,5 +198,19 @@ describe('Scripts (hoisted and not)', () => {
});
expect(found).to.equal(1);
});
it('Injected scripts are injected to injected routes', async () => {
let res = await fixture.fetch('/injected-route');
let html = await res.text();
let $ = cheerio.load(html);
let found = 0;
let moduleScripts = $('[type=module]');
moduleScripts.each((i, el) => {
if ($(el).attr('src').includes('@id/astro:scripts/page.js')) {
found++;
}
});
expect(found).to.equal(1);
});
});
});

View file

@ -0,0 +1,2 @@
export { default as tailwind } from '@astrojs/tailwind';

View file

@ -0,0 +1,11 @@
---
---
<html lang="en">
<head>
<title>External page</title>
</head>
<body>
<h1>My external page</h1>
</body>
</html>