Skip to content

Commit

Permalink
Fix style compilation for file paths containing webpack template stri…
Browse files Browse the repository at this point in the history
…ngs (#1247)
  • Loading branch information
askoufis committed Feb 1, 2024
1 parent 52bf268 commit f0c3be9
Show file tree
Hide file tree
Showing 21 changed files with 186 additions and 4 deletions.
8 changes: 8 additions & 0 deletions .changeset/eleven-oranges-collect.md
@@ -0,0 +1,8 @@
---
'@vanilla-extract/webpack-plugin': patch
---

Fixes a bug that was causing style compilation to fail on paths containing [webpack template strings] such as `[id]` or [Next.js dynamic routes] such as `[slug]`.

[webpack template strings]: https://webpack.js.org/configuration/output/#template-strings
[next.js dynamic routes]: https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes
12 changes: 12 additions & 0 deletions fixtures/template-string-paths/index.html
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.ts"></script>
</body>
</html>
11 changes: 11 additions & 0 deletions fixtures/template-string-paths/package.json
@@ -0,0 +1,11 @@
{
"name": "@fixtures/template-string-paths",
"version": "0.0.1",
"main": "src/index.ts",
"sideEffects": true,
"author": "SEEK",
"private": true,
"dependencies": {
"@vanilla-extract/css": "1.14.1"
}
}
3 changes: 3 additions & 0 deletions fixtures/template-string-paths/src/[...slug]/index.css.ts
@@ -0,0 +1,3 @@
import { style } from '@vanilla-extract/css';

export const catchAllSegment = style({ color: 'lime' });
3 changes: 3 additions & 0 deletions fixtures/template-string-paths/src/[[...slug]]/index.css.ts
@@ -0,0 +1,3 @@
import { style } from '@vanilla-extract/css';

export const optionalCatchAllSegment = style({ color: 'orchid' });
3 changes: 3 additions & 0 deletions fixtures/template-string-paths/src/[[id]]/index.css.ts
@@ -0,0 +1,3 @@
import { style } from '@vanilla-extract/css';

export const doubleSquareBracketId = style({ color: 'darkkhaki' });
3 changes: 3 additions & 0 deletions fixtures/template-string-paths/src/[]/index.css.ts
@@ -0,0 +1,3 @@
import { style } from '@vanilla-extract/css';

export const emptySquareBrackets = style({ color: 'blue' });
3 changes: 3 additions & 0 deletions fixtures/template-string-paths/src/[id]/index.css.ts
@@ -0,0 +1,3 @@
import { style } from '@vanilla-extract/css';

export const singleSquareBracketsId = style({ color: 'tomato' });
20 changes: 20 additions & 0 deletions fixtures/template-string-paths/src/index.ts
@@ -0,0 +1,20 @@
import { emptySquareBrackets } from './[]/index.css';
import { singleSquareBracketsId } from './[id]/index.css';
import { doubleSquareBracketId } from './[[id]]/index.css';
import { catchAllSegment } from './[...slug]/index.css';
import { optionalCatchAllSegment } from './[[...slug]]/index.css';

// Fixture for testing escaping of webpack template strings and Next.js dyanmic routes
// https://webpack.js.org/configuration/output/#template-strings
// https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes
function render() {
document.body.innerHTML = `
<div class="${emptySquareBrackets}">[] path</div>
<div class="${singleSquareBracketsId}">[id] path</div>
<div class="${doubleSquareBracketId}">[[id]] path</div>
<div class="${catchAllSegment}">[...slug] path</div>
<div class="${optionalCatchAllSegment}">[[...slug]] path</div>
`;
}

render();
@@ -0,0 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`escapeWebpackTemplateString() /some/path/[...slug].js pattern 1`] = `"/some/path/[...slug].js"`;

exports[`escapeWebpackTemplateString() /some/path/[[...slug]]/index.js pattern 1`] = `"/some/path/[[...slug]]/index.js"`;

exports[`escapeWebpackTemplateString() /some/path[]/[slug]/[[foo]]/index.js pattern 1`] = `"/some/path[]/[\\slug\\]/[[\\foo\\]]/index.js"`;
11 changes: 11 additions & 0 deletions packages/webpack-plugin/src/compiler.test.ts
@@ -0,0 +1,11 @@
import { escapeWebpackTemplateString } from './compiler';

describe('escapeWebpackTemplateString()', () => {
test.each([
'/some/path/[...slug].js',
'/some/path/[[...slug]]/index.js',
'/some/path[]/[slug]/[[foo]]/index.js',
])('%s pattern', (filePath) => {
expect(escapeWebpackTemplateString(filePath)).toMatchSnapshot();
});
});
15 changes: 13 additions & 2 deletions packages/webpack-plugin/src/compiler.ts
Expand Up @@ -55,6 +55,11 @@ function getRootCompilation(loader: LoaderContext) {
return compilation;
}

const templateStringRegexp = /\[([^\[\]\.]+)\]/g;

export const escapeWebpackTemplateString = (s: string) =>
s.replaceAll(templateStringRegexp, '[\\$1\\]');

function compileVanillaSource(
loader: LoaderContext,
externals: Externals | undefined,
Expand All @@ -64,9 +69,15 @@ function compileVanillaSource(
loader._compiler.webpack && loader._compiler.webpack.version,
);
const compat = createCompat(isWebpack5);
// Child compiler will compile vanilla-extract files to be evaled during compilation
const outputOptions = { filename: loader.resourcePath };

// Escape webpack template strings and Next.js dynamic routes in output files so they don't get replaced
// Non-standard escape syntax, see https://webpack.js.org/configuration/output/#template-strings
// and https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes
const outputOptions = {
filename: escapeWebpackTemplateString(loader.resourcePath),
};

// Child compiler will compile vanilla-extract files to be evaled during compilation
const compilerName = getCompilerName(loader.resourcePath);
const childCompiler = getRootCompilation(loader).createChildCompiler(
compilerName,
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

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

1 change: 1 addition & 0 deletions test-helpers/package.json
Expand Up @@ -12,6 +12,7 @@
"@fixtures/low-level": "*",
"@fixtures/recipes": "*",
"@fixtures/sprinkles": "*",
"@fixtures/template-string-paths": "*",
"@fixtures/themed": "*",
"@fixtures/thirdparty": "*",
"@fixtures/unused-modules": "*",
Expand Down
43 changes: 43 additions & 0 deletions tests/e2e/template-string-paths.playwright.ts
@@ -0,0 +1,43 @@
import { expect } from '@playwright/test';
import {
getStylesheet,
startFixture,
TestServer,
} from '@vanilla-extract-private/test-helpers';

import test from './fixture';
import { webpack as testCases } from './testCases';

testCases.forEach(({ type, mode, snapshotCss = true }) => {
test.describe(`template-string-paths - ${type} (${mode})`, () => {
let server: TestServer;

test.beforeAll(async ({ port }) => {
server = await startFixture('template-string-paths', {
type,
mode,
basePort: port,
});
});

test('screenshot', async ({ page }) => {
await page.goto(server.url);

expect(await page.screenshot()).toMatchSnapshot(
'template-string-paths.png',
);
});

if (snapshotCss) {
test('CSS @agnostic', async () => {
expect(
await getStylesheet(server.url, server.stylesheet),
).toMatchSnapshot(`template-string-paths-${type}--${mode}.css`);
});
}

test.afterAll(async () => {
await server.close();
});
});
});
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@@ -0,0 +1,15 @@
.\[\]_emptySquareBrackets__13abg9g0 {
color: blue;
}
.\[id\]_singleSquareBracketsId__1d2wsrw0 {
color: tomato;
}
.\[\[id\]\]_doubleSquareBracketId__1aosxxv0 {
color: darkkhaki;
}
.\[\.\.\.slug\]_catchAllSegment__169etlp0 {
color: lime;
}
.\[\[\.\.\.slug\]\]_optionalCatchAllSegment__1kvknas0 {
color: orchid;
}
@@ -0,0 +1,15 @@
._13abg9g0 {
color: blue;
}
._1d2wsrw0 {
color: tomato;
}
._1aosxxv0 {
color: darkkhaki;
}
._169etlp0 {
color: lime;
}
._1kvknas0 {
color: orchid;
}
6 changes: 5 additions & 1 deletion tests/e2e/testCases.ts
@@ -1,7 +1,11 @@
export const all = [
export const webpack = [
{ type: 'mini-css-extract', mode: 'development', snapshotCss: true },
{ type: 'mini-css-extract', mode: 'production', snapshotCss: true },
{ type: 'style-loader', mode: 'development', snapshotCss: false },
] as const;

export const all = [
...webpack,
{ type: 'esbuild', mode: 'development', snapshotCss: true },
{ type: 'esbuild', mode: 'production', snapshotCss: true },
{ type: 'esbuild-runtime', mode: 'development', snapshotCss: false },
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Expand Up @@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ESNEXT" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": ["es2019", "es2017", "dom"],
"lib": ["es2021", "dom"],
"noEmit": true,
"noImplicitAny": true,
"noUnusedLocals": true,
Expand Down

0 comments on commit f0c3be9

Please sign in to comment.