Skip to content

Commit

Permalink
Handle issue where <style> does not exist when hoisting
Browse files Browse the repository at this point in the history
  • Loading branch information
winston0410 committed Aug 21, 2021
1 parent 9d7a3ae commit c7f8111
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/transformer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import MagicString from "magic-string";
import { walk } from "svelte/compiler";
import { assembleRules } from "./helper.js";

export default function (code, {dir, base}) {
export default function (code, { dir, base }) {
const changeable = new MagicString(code);

return {
transformCss(ast, cache) {
if (!ast && Object.keys(cache).length > 0) {
changeable.appendRight(0, `<style>${assembleRules(cache)}</style>`);
return this;
}
walk(ast, {
enter(node) {
switch (node.type) {
Expand Down
36 changes: 36 additions & 0 deletions test/transformer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,39 @@ describe("when transforming html", function () {
);
});
});

describe("when transforming css", function () {
describe("when <style> does not exist", function () {
const code = `<p>hello</p>`;
const filename = `/src/routes/__layout.svelte`;

const declarationCache = {
none: {
"font-size:100px;": "a",
},
};

describe("when given an non-empty declaration cache", function () {
const ast = parse(code, { filename });
const parsedPath = path.parse(filename);
const transformer = createTransformer(code, parsedPath).transformCss(
ast.css,
declarationCache
);
it("should insert the styling correctly", async () => {
const result = transformer.toString();

expect(result.replace(/\s/g, "")).toBe(
`<style>
:global(.a){
font-size: 100px;
}
</style>
<p>hello</p>
`.replace(/\s/g, "")
);
});
});
});
});

0 comments on commit c7f8111

Please sign in to comment.