Implement new default script behavior, style is:global (#2961)

* feat: implement RFC0016

* chore: update to latest compiler

* chore: update compiler

* test: fix script tests

* test: update public tests

* feat: throw a warning when referencing scripts in `public/` without `is:inline`
This commit is contained in:
Nate Moore 2022-04-02 12:34:25 -05:00 committed by GitHub
parent 42760e07ca
commit d55658f061
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 46 additions and 32 deletions

View file

@ -0,0 +1,5 @@
---
'astro': minor
---
Implement [RFC0016](https://github.com/withastro/rfcs/blob/main/proposals/0016-style-script-defaults.md) which changes the default behavior of `script`, introduces `is:inline`, and changes `<style global>` to `<style is:global>`

View file

@ -7,7 +7,7 @@ import * as Component from '@example/my-component';
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Welcome to Astro</title>
<style global>
<style is:global>
h {
display: block;
font-size: 2em;

View file

@ -5,7 +5,8 @@
<button class="py-2 px-4 bg-purple-500 text-white font-semibold rounded-lg shadow-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-400 focus:ring-opacity-75">
<slot />
</button>
<script hoist>
<script>
import confetti from 'canvas-confetti';
document.body.querySelector('button').addEventListener("click", () => confetti());
</script>
</script>

View file

@ -73,7 +73,7 @@
"test:match": "mocha --timeout 20000 -g"
},
"dependencies": {
"@astrojs/compiler": "^0.13.2",
"@astrojs/compiler": "^0.14.1",
"@astrojs/language-server": "^0.13.2",
"@astrojs/markdown-remark": "^0.7.0",
"@astrojs/prism": "0.4.1",

View file

@ -122,10 +122,9 @@ export function createResult(args: CreateResultArgs): SSRResult {
let extra = `This can be replaced with a dynamic import like so: await import("${path}")`;
if (isCSSRequest(path)) {
extra = `It looks like you are resolving styles. If you are adding a link tag, replace with this:
<style global>
@import "${path}";
</style>
---
import "${path}";
---
`;
} else if (isScriptRequest(path)) {
extra = `It looks like you are resolving scripts. If you are adding a script tag, replace with this:
@ -134,7 +133,7 @@ export function createResult(args: CreateResultArgs): SSRResult {
or consider make it a module like so:
<script type="module" hoist>
<script>
import MyModule from "${path}";
</script>
`;

View file

@ -535,16 +535,17 @@ function getHTMLElementName(constructor: typeof HTMLElement) {
}
function renderElement(name: string, { props: _props, children = '' }: SSRElement, shouldEscape = true) {
// Do not print `hoist`, `lang`, `global`
// Do not print `hoist`, `lang`, `is:global`
const { lang: _, 'data-astro-id': astroId, 'define:vars': defineVars, ...props } = _props;
if (defineVars) {
if (name === 'style') {
if (props.global) {
if (props['is:global']) {
children = defineStyleVars(`:root`, defineVars) + '\n' + children;
} else {
children = defineStyleVars(`.astro-${astroId}`, defineVars) + '\n' + children;
}
delete props.global;
delete props['is:global'];
delete props['is:scoped'];
}
if (name === 'script') {
delete props.hoist;

View file

@ -63,7 +63,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
const { query: fromQuery, filename } = parseAstroRequest(from);
if (fromQuery.astro && isRelativePath(id) && fromQuery.type === 'script') {
const resolvedURL = new URL(id, `file://${filename}`);
const resolved = resolvedURL.pathname;
const resolved = resolvedURL.pathname
if (isBrowserPath(resolved)) {
return relativeToRoot(resolved + resolvedURL.search);
}
@ -96,7 +96,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
let source = await fs.promises.readFile(fileUrl, 'utf-8');
const isPage = fileUrl.pathname.startsWith(config.pages.pathname);
if (isPage && config._ctx.scripts.some((s) => s.stage === 'page')) {
source += `\n<script hoist src="${PAGE_SCRIPT_ID}" />`;
source += `\n<script src="${PAGE_SCRIPT_ID}" />`;
}
if (query.astro) {
if (query.type === 'style') {
@ -127,6 +127,14 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
throw new Error(`No hoisted script at index ${query.index}`);
}
if (hoistedScript.type === 'external') {
const src = hoistedScript.src!;
if (src.startsWith('/') && !isBrowserPath(src)) {
const publicDir = config.public.pathname.replace(/\/$/, '').split('/').pop() + '/';
throw new Error(`\n\n<script src="${src}"> references an asset in the "${publicDir}" directory. Please add the "is:inline" directive to keep this asset from being bundled.\n\nFile: ${filename}`)
}
}
return {
code: hoistedScript.type === 'inline' ? hoistedScript.code! : `import "${hoistedScript.src!}";`,
};

View file

@ -12,7 +12,7 @@ describe('Public', () => {
it('css and js files do not get bundled', async () => {
let indexHtml = await fixture.readFile('/index.html');
expect(indexHtml).to.include('<script src="/example.js"></script>');
expect(indexHtml).to.include('<link href="/example.css" ref="stylesheet">');
expect(indexHtml).to.include('<link href="/example.css" rel="stylesheet">');
expect(indexHtml).to.include('<img src="/images/twitter.png">');
});
});

View file

@ -19,7 +19,7 @@
}
</style>
<style global>
<style is:global>
html {
--primary: aquamarine;
}

View file

@ -1,10 +1,10 @@
<html lang="en">
<head>
<title>This Site</title>
<link href="/example.css" ref="stylesheet"/>
<script src="/example.js"></script>
<link href="/example.css" rel="stylesheet"/>
<script is:inline src="/example.js"></script>
</head>
<body>
<img src="/images/twitter.png" />
</body>
</html>
</html>

View file

@ -1,3 +1,3 @@
<script hoist type="module">
<script>
console.log('some content here.');
</script>
</script>

View file

@ -1,4 +1,4 @@
---
import url from "../scripts/no_hoist_nonmodule.js?url"
---
<script src={url}></script>
<script is:inline src={url}></script>

View file

@ -1,4 +1,4 @@
---
import url from '../scripts/no_hoist_module.js?url';
---
<script type="module" src={url}></script>
<script is:inline type="module" src={url}></script>

View file

@ -1 +1 @@
<script hoist type="module" src="../scripts/something.js"></script>
<script src="../scripts/something.js"></script>

View file

@ -1 +1 @@
<script hoist type="module" src="../scripts/another_external.js"></script>
<script src="../scripts/another_external.js"></script>

View file

@ -16,4 +16,4 @@ import Widget2 from '../components/Widget2.astro';
<Widget />
<Widget2 />
</body>
</html>
</html>

View file

@ -1,5 +1,5 @@
<style global>
<style is:global>
/* Testing remote imports */
@import "https://unpkg.com/open-props";
@import "https://unpkg.com/open-props/normalize.min.css";
</style>
</style>

View file

@ -442,7 +442,7 @@ importers:
packages/astro:
specifiers:
'@astrojs/compiler': ^0.13.2
'@astrojs/compiler': ^0.14.1
'@astrojs/language-server': ^0.13.2
'@astrojs/markdown-remark': ^0.7.0
'@astrojs/prism': 0.4.1
@ -528,7 +528,7 @@ importers:
yargs-parser: ^21.0.1
zod: ^3.14.3
dependencies:
'@astrojs/compiler': 0.13.2
'@astrojs/compiler': 0.14.1
'@astrojs/language-server': 0.13.2
'@astrojs/markdown-remark': link:../markdown/remark
'@astrojs/prism': link:../astro-prism
@ -1713,8 +1713,8 @@ packages:
leven: 3.1.0
dev: true
/@astrojs/compiler/0.13.2:
resolution: {integrity: sha512-0Un4CtLbhJljisFf9WaxK1TSV1oakR3Mh4x1Uyg1JHdyQ5te/1xcq+PWVaOyQc4lq4z8MYNFQb7hG66m0CeMtw==}
/@astrojs/compiler/0.14.1:
resolution: {integrity: sha512-dYgb52JvZE8jyDg84JkdJ/dTxRgHVbC47ou6Ymok/nZDh9kvlU7TJtEDCLlGfpfZTGvnkFTHMrz1kdbqCbFVCw==}
dependencies:
tsm: 2.2.1
uvu: 0.5.3