Use of PUBLIC_ environment variables (#2044)

* Enable client-side JS to read env variables via PUBLIC_

* Fixes use of PUBLIC_ in client-JS
This commit is contained in:
Matthew Phillips 2021-11-29 14:22:46 -05:00 committed by GitHub
parent 0aeb92be6f
commit fad6bd0936
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 48 additions and 0 deletions

View file

@ -0,0 +1,7 @@
---
'astro': patch
---
Fixes use of `PUBLIC_` to reference env vars
Previously `PUBLIC_` worked in server-only components such as .astro components. However if you had a client-side component you had to use `VITE_`. This was a bug with our build that is now fixed.

View file

@ -203,6 +203,7 @@ class AstroBuilder {
],
publicDir: viteConfig.publicDir,
root: viteConfig.root,
envPrefix: 'PUBLIC_',
server: viteConfig.server,
base: this.config.buildOptions.site ? new URL(this.config.buildOptions.site).pathname : '/',
});

View file

@ -20,4 +20,23 @@ describe('Environment Variables', () => {
expect(indexHtml).to.not.include('CLUB_33');
expect(indexHtml).to.include('BLUE_BAYOU');
});
it('includes public env in client-side JS', async () => {
let dirs = await fixture.readdir('/assets');
let found = false;
// Look in all of the .js files to see if the public env is inlined.
// Testing this way prevents hardcoding expected js files.
// If we find it in any of them that's good enough to know its working.
await Promise.all(dirs.map(async path => {
if(path.endsWith('.js')) {
let js = await fixture.readFile(`/assets/${path}`);
if(js.includes('BLUE_BAYOU')) {
found = true;
}
}
}));
expect(found).to.equal(true, 'found the env variable in the JS build');
});
});

View file

@ -0,0 +1,15 @@
<template>
<div id="client-component">
{{ PUBLIC_PLACE }}
</div>
</template>
<script>
export default {
data() {
return {
PUBLIC_PLACE: import.meta.env.PUBLIC_PLACE,
};
},
};
</script>

View file

@ -1,2 +1,6 @@
---
import Client from '../components/Client.vue';
---
<environment-variable>{import.meta.env.PUBLIC_PLACE}</environment-variable>
<environment-variable>{import.meta.env.SECRET_PLACE}</environment-variable>
<Client client:load />

View file

@ -15,6 +15,7 @@ import preview from '../dist/core/preview/index.js';
* @property {typeof build} build
* @property {(url: string, opts: any) => Promise<Response>} fetch
* @property {(path: string) => Promise<string>} readFile
* @property {(path: string) => Promise<string[]>} readdir
* @property {() => Promise<DevServer>} startDevServer
*/
@ -70,6 +71,7 @@ export async function loadFixture(inlineConfig) {
return previewServer;
},
readFile: (filePath) => fs.promises.readFile(new URL(filePath.replace(/^\//, ''), config.dist), 'utf8'),
readdir: (fp) => fs.promises.readdir(new URL(fp.replace(/^\//, ''), config.dist))
};
}