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 style compilation for file paths containing webpack template strings #1247

Merged
merged 14 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
7 changes: 7 additions & 0 deletions .changeset/eleven-oranges-collect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@vanilla-extract/webpack-plugin': patch
---

Fixes a bug that was causing style compilation to fail on paths containing [webpack template strings] such as `[id]`.

[webpack template strings]: https://webpack.js.org/configuration/output/#template-strings
12 changes: 12 additions & 0 deletions fixtures/template-string-paths/index.html
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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();
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ function getRootCompilation(loader: LoaderContext) {
return compilation;
}

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

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

@askoufis askoufis Jan 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with the $1 syntax as my assumption is that it's less overhead compared to creating a replacement function.


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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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';
Copy link
Contributor Author

@askoufis askoufis Jan 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chose to restrict this fixture to only run using webpack.


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();
});
});
});
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -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;
}
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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"],
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Required for tsc to recognize replaceAll. It was added in node 15, so IMO it's safe to use.

"noEmit": true,
"noImplicitAny": true,
"noUnusedLocals": true,
Expand Down
Loading