Skip to content

Commit c7f8111

Browse files
committed
Handle issue where <style> does not exist when hoisting
1 parent 9d7a3ae commit c7f8111

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/transformer.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@ import MagicString from "magic-string";
22
import { walk } from "svelte/compiler";
33
import { assembleRules } from "./helper.js";
44

5-
export default function (code, {dir, base}) {
5+
export default function (code, { dir, base }) {
66
const changeable = new MagicString(code);
77

88
return {
99
transformCss(ast, cache) {
10+
if (!ast && Object.keys(cache).length > 0) {
11+
changeable.appendRight(0, `<style>${assembleRules(cache)}</style>`);
12+
return this;
13+
}
1014
walk(ast, {
1115
enter(node) {
1216
switch (node.type) {

test/transformer.spec.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,39 @@ describe("when transforming html", function () {
4343
);
4444
});
4545
});
46+
47+
describe("when transforming css", function () {
48+
describe("when <style> does not exist", function () {
49+
const code = `<p>hello</p>`;
50+
const filename = `/src/routes/__layout.svelte`;
51+
52+
const declarationCache = {
53+
none: {
54+
"font-size:100px;": "a",
55+
},
56+
};
57+
58+
describe("when given an non-empty declaration cache", function () {
59+
const ast = parse(code, { filename });
60+
const parsedPath = path.parse(filename);
61+
const transformer = createTransformer(code, parsedPath).transformCss(
62+
ast.css,
63+
declarationCache
64+
);
65+
it("should insert the styling correctly", async () => {
66+
const result = transformer.toString();
67+
68+
expect(result.replace(/\s/g, "")).toBe(
69+
`<style>
70+
:global(.a){
71+
font-size: 100px;
72+
}
73+
</style>
74+
75+
<p>hello</p>
76+
`.replace(/\s/g, "")
77+
);
78+
});
79+
});
80+
});
81+
});

0 commit comments

Comments
 (0)