From 4ee66cbc84ee92bf1cf3b8842dfa2d9f96122409 Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Tue, 24 May 2022 16:21:56 -0400 Subject: [PATCH] Prevent including module metadata imports for side-effectual CSS (#410) * Prevent including module metadata imports for side-effectual CSS * Adds a changeset * Change escaping for lint * Update expression --- .changeset/shiny-dots-care.md | 5 +++++ internal/printer/printer.go | 18 ++++++++++++++---- internal/printer/printer_test.go | 13 +++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 .changeset/shiny-dots-care.md diff --git a/.changeset/shiny-dots-care.md b/.changeset/shiny-dots-care.md new file mode 100644 index 000000000..f0c28b016 --- /dev/null +++ b/.changeset/shiny-dots-care.md @@ -0,0 +1,5 @@ +--- +'@astrojs/compiler': patch +--- + +Prevent side-effectual CSS imports from becoming module metadata diff --git a/internal/printer/printer.go b/internal/printer/printer.go index 0186448af..06f52887a 100644 --- a/internal/printer/printer.go +++ b/internal/printer/printer.go @@ -2,6 +2,7 @@ package printer import ( "fmt" + "regexp" "strings" astro "github.com/withastro/compiler/internal" @@ -43,6 +44,7 @@ var RESULT = "$$result" var SLOTS = "$$slots" var FRAGMENT = "Fragment" var BACKTICK = "`" +var styleModuleSpecExp = regexp.MustCompile(`(\.css|\.pcss|\.postcss|\.sass|\.scss|\.styl|\.stylus|\.less)$`) func (p *printer) print(text string) { p.output = append(p.output, text...) @@ -441,10 +443,18 @@ func (p *printer) printComponentMetadata(doc *astro.Node, opts transform.Transfo assertions += " assert " assertions += statement.Assertions } - p.print(fmt.Sprintf("\nimport * as $$module%v from '%s'%s;", modCount, statement.Specifier, assertions)) - specs = append(specs, statement.Specifier) - asrts = append(asrts, statement.Assertions) - modCount++ + + isCssImport := false + if len(statement.Imports) == 0 && styleModuleSpecExp.MatchString(statement.Specifier) { + isCssImport = true + } + + if !isCssImport { + p.print(fmt.Sprintf("\nimport * as $$module%v from '%s'%s;", modCount, statement.Specifier, assertions)) + specs = append(specs, statement.Specifier) + asrts = append(asrts, statement.Assertions) + modCount++ + } } loc, statement = js_scanner.NextImportStatement(source, loc) } diff --git a/internal/printer/printer_test.go b/internal/printer/printer_test.go index bb686b4be..e0b039e76 100644 --- a/internal/printer/printer_test.go +++ b/internal/printer/printer_test.go @@ -221,6 +221,19 @@ import data from "test" assert { type: 'json' }; code: `

Hello, world! This is a buggy formula: f ⁣:XR2xf\\colon X \\to \\mathbb R^{2x}

`, }, }, + { + name: "css imports are not included in module metadata", + source: `--- + import './styles.css'; + --- + `, + want: want{ + frontmatter: []string{ + `import './styles.css';`, + }, + styles: []string{}, + }, + }, { name: "solidus in template literal expression", source: "
",