Make fetch available in all component types (#949)

* Make fetch available in all component types

This makes `globalThis.fetch` available in all components.

* Adds a changeset
This commit is contained in:
Matthew Phillips 2021-08-03 13:13:00 -04:00 committed by GitHub
parent fc739c24d7
commit 39df7952a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 49 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Makes `fetch` available in all framework components

View file

@ -115,6 +115,10 @@ export async function compileComponent(source: string, { compileOptions, filenam
import fetch from 'node-fetch';
${result.imports.join('\n')}
if(!('fetch' in globalThis)) {
globalThis.fetch = fetch;
}
${/* Global Astro Namespace (shadowed & extended by the scoped namespace inside of __render()) */ ''}
const __TopLevelAstro = {
site: new URL(${JSON.stringify(site)}),

View file

@ -0,0 +1,18 @@
import { suite } from 'uvu';
import * as assert from 'uvu/assert';
import { doc } from './test-utils.js';
import { setup } from './helpers.js';
const Fetch = suite('Global Fetch');
setup(Fetch, './fixtures/fetch');
Fetch('Is available in non-Astro components.', async ({ runtime }) => {
const result = await runtime.load('/');
assert.ok(!result.error, `build error: ${result.error}`);
const $ = doc(result.contents);
assert.equal($('#jsx').text(), 'function');
});
Fetch.run();

View file

@ -0,0 +1,3 @@
{
"workspaceRoot": "../../../../../"
}

View file

@ -0,0 +1,7 @@
import { h } from 'preact';
export default function() {
return (
<span id="jsx">{ typeof fetch }</span>
);
}

View file

@ -0,0 +1,12 @@
---
import Child from '../components/Child.jsx';
---
<html lang="en">
<head>
<title>Global fetch</title>
</head>
<body>
<Child />
</body>
</html>