Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix importing CSS packages in frontmatter #3537

Merged
merged 6 commits into from
Jun 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/green-ducks-reply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes imported CSS packages in frontmatter
2 changes: 1 addition & 1 deletion packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
"strip-ansi": "^7.0.1",
"supports-esm": "^1.0.0",
"tsconfig-resolver": "^3.0.1",
"vite": "^2.9.9",
"vite": "^2.9.10",
"yargs-parser": "^21.0.1",
"zod": "^3.17.3"
},
Expand Down
70 changes: 34 additions & 36 deletions packages/astro/src/vite-plugin-build-css/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { GetModuleInfo, ModuleInfo } from 'rollup';
import type { GetModuleInfo, ModuleInfo, OutputChunk } from 'rollup';
import { BuildInternals } from '../core/build/internal';
import type { PageBuildData } from '../core/build/types';

Expand Down Expand Up @@ -76,25 +76,6 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[]
{
name: CSS_PLUGIN_NAME,

configResolved(resolvedConfig) {
// Our plugin needs to run before `vite:css-post` because we have to modify
// The bundles before vite:css-post sees them. We can remove this code
// after this bug is fixed: https://github.com/vitejs/vite/issues/8330
const plugins = resolvedConfig.plugins as VitePlugin[];
const viteCSSPostIndex = resolvedConfig.plugins.findIndex(
(p) => p.name === 'vite:css-post'
);
if (viteCSSPostIndex !== -1) {
// Move our plugin to be right before this one.
const ourIndex = plugins.findIndex((p) => p.name === CSS_PLUGIN_NAME);
const ourPlugin = plugins[ourIndex];

// Remove us from where we are now and place us right before the viteCSSPost plugin
plugins.splice(ourIndex, 1);
plugins.splice(viteCSSPostIndex - 1, 0, ourPlugin);
}
},

outputOptions(outputOptions) {
const manualChunks = outputOptions.manualChunks || Function.prototype;
outputOptions.manualChunks = function (id, ...args) {
Expand Down Expand Up @@ -157,21 +138,8 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[]
}
}
}

if (chunk.type === 'chunk') {
// This simply replaces single quotes with double quotes because the vite:css-post
// plugin only works with single for some reason. This code can be removed
// When the Vite bug is fixed: https://github.com/vitejs/vite/issues/8330
const exp = new RegExp(
`(\\bimport\\s*)[']([^']*(?:[a-z]+\.[0-9a-z]+\.m?js))['](;\n?)`,
'g'
);
chunk.code = chunk.code.replace(exp, (_match, begin, chunkPath, end) => {
return begin + '"' + chunkPath + '"' + end;
});
}
}
},
}
},
{
name: CSS_MINIFY_PLUGIN_NAME,
Expand All @@ -190,10 +158,40 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[]
});
output.source = minifiedCSS;
}
} else if (output.type === 'chunk') {
// vite:css-post removes "pure CSS" JavaScript chunks, that is chunks that only contain a comment
// about it being a CSS module. We need to keep these chunks around because Astro
// re-imports all modules as their namespace `import * as module1 from 'some/path';
// in order to determine if one of them is a side-effectual web component.
// If we ever get rid of that feature, the code below can be removed.
for(const [imp, bindings] of Object.entries(output.importedBindings)) {
if(imp.startsWith('chunks/') && !bundle[imp] && output.code.includes(imp)) {
// This just creates an empty chunk module so that the main entry module
// that is importing it doesn't break.
const depChunk: OutputChunk = {
type: 'chunk',
fileName: imp,
name: imp,
facadeModuleId: imp,
code: `/* Pure CSS chunk ${imp} */ ${bindings.map(b => `export const ${b} = {};`)}`,
dynamicImports: [],
implicitlyLoadedBefore: [],
importedBindings: {},
imports: [],
referencedFiles: [],
exports: Array.from(bindings),
isDynamicEntry: false,
isEntry: false,
isImplicitEntry: false,
modules: {},
};
bundle[imp] = depChunk;
}
}
}
}
}
},
},
}
}
];
}
9 changes: 9 additions & 0 deletions packages/astro/test/fixtures/fontsource-package/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@test/astro-fontsource-package",
"version": "0.0.0",
"private": true,
"dependencies": {
"@fontsource/montserrat": "4.5.11",
"astro": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
import "@fontsource/montserrat";
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Astro</title>
</head>
<body>
<h1>Astro</h1>
</body>
</html>
20 changes: 20 additions & 0 deletions packages/astro/test/fontsource.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { expect } from 'chai';
import * as cheerio from 'cheerio';
import { loadFixture } from './test-utils.js';

describe('@fontsource/* packages', () => {
let fixture;

before(async () => {
fixture = await loadFixture({ root: './fixtures/fontsource-package/' });
await fixture.build();
});

it('can be imported in frontmatter', async () => {
const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html);
const assetPath = $('link').attr('href');
const css = await fixture.readFile(assetPath);
expect(css).to.contain('Montserrat');
});
});
24 changes: 18 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.