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

Support identifier formatting configuration #323

Merged
merged 14 commits into from
Aug 27, 2021
3 changes: 3 additions & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@
"access": "public",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": {
"onlyUpdatePeerDependentsWhenOutOfRange": true
},
"ignore": ["@fixtures/*", "test-helpers", "vanilla-extract-webpack-react"]
}
21 changes: 21 additions & 0 deletions .changeset/gold-wombats-thank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@vanilla-extract/snowpack-plugin': major
---

Formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc) can now be configured via the `identifiers` option which accepts either `short` or `debug`.

- `short` identifiers are a 7+ character hash. e.g. `hnw5tz3`
- `debug` identifiers contain human readable prefixes representing the owning filename and a potential rule level debug name. e.g. `somefile_mystyle_hnw5tz3`

```js
import { vanillaExtractPlugin } from '@vanilla-extract/snowpack-plugin';

const snowpackConfig = {
plugins: [['@vanilla-extract/snowpack-plugin', { identifiers: 'short' }]]
}
```

BREAKING CHANGE

Previously identifiers were formatted as `short` when `process.env.NODE_ENV` was set to "production". By default, they will now be formatted according to Snowpacks's [mode config](https://www.snowpack.dev/reference/configuration#mode).

19 changes: 19 additions & 0 deletions .changeset/hip-icons-destroy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@vanilla-extract/webpack-plugin': major
---

Formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc) can now be configured via the `identifiers` option which accepts either `short` or `debug`.

- `short` identifiers are a 7+ character hash. e.g. `hnw5tz3`
- `debug` identifiers contain human readable prefixes representing the owning filename and a potential rule level debug name. e.g. `somefile_mystyle_hnw5tz3`

```js
import { vanillaExtractPlugin } from '@vanilla-extract/webpack-plugin';

vanillaExtractPlugin({ identifiers: 'short' })
```

BREAKING CHANGE

Previously identifiers were formatted as `short` when `process.env.NODE_ENV` was set to "production". By default, they will now be formatted according to webpack's [mode config](https://webpack.js.org/configuration/mode/).

5 changes: 5 additions & 0 deletions .changeset/neat-pillows-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vanilla-extract/sprinkles': patch
---

Update `@vanilla-extract/css` dependency to `^1.0.0`
18 changes: 18 additions & 0 deletions .changeset/olive-zoos-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@vanilla-extract/vite-plugin': major
---

Formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc) can now be configured via the `identifiers` option which accepts either `short` or `debug`.

- `short` identifiers are a 7+ character hash. e.g. `hnw5tz3`
- `debug` identifiers contain human readable prefixes representing the owning filename and a potential rule level debug name. e.g. `somefile_mystyle_hnw5tz3`

```js
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';

vanillaExtractPlugin({ identifiers: 'short' });
```

BREAKING CHANGE

Previously identifiers were formatted as `short` when `process.env.NODE_ENV` was set to "production". By default, they will now be formatted according to Vite's [mode config](https://vitejs.dev/config/#mode).
18 changes: 18 additions & 0 deletions .changeset/sharp-dingos-smell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@vanilla-extract/esbuild-plugin': major
---

Formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc) can now be configured via the `identifiers` option which accepts either `short` or `debug`.

- `short` identifiers are a 7+ character hash. e.g. `hnw5tz3`
- `debug` identifiers contain human readable prefixes representing the owning filename and a potential rule level debug name. e.g. `somefile_mystyle_hnw5tz3`

```js
import { vanillaExtractPlugin } from '@vanilla-extract/esbuild-plugin';

vanillaExtractPlugin({ identifiers: 'short' });
```

BREAKING CHANGE

Previously identifiers were formatted as `short` when `process.env.NODE_ENV` was set to "production". By default, they will now be formatted according to esbuild's [minify config](https://esbuild.github.io/api/#minify).
6 changes: 6 additions & 0 deletions .changeset/twenty-cougars-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@vanilla-extract/css': minor
'@vanilla-extract/integration': minor
---

Support configurable identifier types
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ Want to work at a higher level while maximising style re-use? Check out 🍨 [S
- [Snowpack](#snowpack)
- [Gatsby](#gatsby)
- [Test environments](#test-environments)
- [Configuration](#configuration)
- [identifiers](#identifiers)
- [Styling API](#styling-api)
- [style](#style)
- [styleVariants](#stylevariants)
Expand Down Expand Up @@ -132,6 +134,8 @@ npm install @vanilla-extract/css @vanilla-extract/babel-plugin @vanilla-extract/

3. Add the [webpack](https://webpack.js.org) plugin.

> 💡 This plugin accepts an optional [configuration object](#configuration).

```js
const { VanillaExtractPlugin } = require('@vanilla-extract/webpack-plugin');

Expand Down Expand Up @@ -185,6 +189,8 @@ npm install @vanilla-extract/css @vanilla-extract/esbuild-plugin

2. Add the [esbuild](https://esbuild.github.io/) plugin to your build script.

> 💡 This plugin accepts an optional [configuration object](#configuration).

```js
const { vanillaExtractPlugin } = require('@vanilla-extract/esbuild-plugin');

Expand All @@ -198,7 +204,7 @@ require('esbuild').build({

> Please note: There are currently no automatic readable class names during development. However, you can still manually provide a debug ID as the last argument to functions that generate scoped styles, e.g. `export const className = style({ ... }, 'className');`

3. Process CSS
1. Process CSS
mattcompiles marked this conversation as resolved.
Show resolved Hide resolved

As [esbuild](https://esbuild.github.io/) currently doesn't have a way to process the CSS generated by vanilla-extract, you can optionally use the `processCss` option.

Expand Down Expand Up @@ -246,6 +252,8 @@ npm install @vanilla-extract/css @vanilla-extract/vite-plugin

2. Add the [Vite](https://vitejs.dev/) plugin to your Vite config.

> 💡 This plugin accepts an optional [configuration object](#configuration).

```js
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';

Expand All @@ -267,6 +275,8 @@ npm install @vanilla-extract/css @vanilla-extract/snowpack-plugin

2. Add the [Snowpack](https://www.snowpack.dev/) plugin to your snowpack config.

> 💡 This plugin accepts an optional [configuration object](#configuration).

```js
// snowpack.config.json
{
Expand Down Expand Up @@ -305,6 +315,16 @@ In testing environments (like `jsdom`) vanilla-extract will create and insert st
import '@vanilla-extract/css/disableRuntimeStyles';
```

### Configuration

#### identifiers

Different formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc) can be configured by selecting from the following options:

- `short` identifiers are a 7+ character hash. e.g. `hnw5tz3`
- `debug` identifiers contain human readable prefixes representing the owning filename and a potential rule level debug name. e.g. `myfile_mystyle_hnw5tz3`

Each integration will set a default value based on the configuration options passed to the bundler.

---

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@
"@babel/preset-env": "^7.13.15",
"@babel/preset-react": "^7.13.13",
"@babel/preset-typescript": "^7.13.0",
"@changesets/changelog-github": "^0.3.0",
"@changesets/cli": "^2.14.1",
"@changesets/changelog-github": "^0.4.0",
"@changesets/cli": "^2.16.0",
"@manypkg/cli": "^0.17.0",
"@preconstruct/cli": "^2.0.1",
"@testing-library/dom": "^7.30.0",
Expand Down
10 changes: 10 additions & 0 deletions packages/css/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const mockAdapter: Adapter = {
onEndFileScope: () => {},
registerComposition: () => {},
markCompositionUsed: () => {},
getIdentOption: () => 'debug',
};

let adapter: Adapter = mockAdapter;
Expand Down Expand Up @@ -46,3 +47,12 @@ export const markCompositionUsed: Adapter['markCompositionUsed'] = (
export const onEndFileScope: Adapter['onEndFileScope'] = (...props) => {
return adapter.onEndFileScope(...props);
};

export const getIdentOption: Adapter['getIdentOption'] = (...props) => {
// Backwards compatibility with old versions of the integration package
if (!('getIdentOption' in adapter)) {
return process.env.NODE_ENV === 'production' ? 'short' : 'debug';
}

return adapter.getIdentOption(...props);
};
3 changes: 2 additions & 1 deletion packages/css/src/identifier.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import hash from '@emotion/hash';

import { getIdentOption } from './adapter';
import { getAndIncrementRefCounter, getFileScope } from './fileScope';

function getDevPrefix(debugId: string | undefined) {
Expand Down Expand Up @@ -29,7 +30,7 @@ export function generateIdentifier(debugId: string | undefined) {

let identifier = `${fileScopeHash}${refCount}`;

if (process.env.NODE_ENV !== 'production') {
if (getIdentOption() === 'debug') {
const devPrefix = getDevPrefix(debugId);

if (devPrefix) {
Expand Down
2 changes: 2 additions & 0 deletions packages/css/src/runtimeAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ const browserRuntimeAdapter: Adapter = {

bufferedCSSObjs = [];
},
getIdentOption: () =>
process.env.NODE_ENV === 'production' ? 'short' : 'debug',
};

if (typeof window !== 'undefined') {
Expand Down
3 changes: 3 additions & 0 deletions packages/css/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,15 @@ export interface Composition {
identifier: string;
classList: string;
}

type IdentOption = 'short' | 'debug';
export interface Adapter {
appendCss: (css: CSS, fileScope: FileScope) => void;
registerClassName: (className: string) => void;
registerComposition: (composition: Composition) => void;
markCompositionUsed: (identifier: string) => void;
onEndFileScope: (fileScope: FileScope) => void;
getIdentOption: () => IdentOption;
}

export type NullableTokens = {
Expand Down
3 changes: 2 additions & 1 deletion packages/css/src/vars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import cssesc from 'cssesc';
import { Tokens, NullableTokens, ThemeVars } from './types';
import { getAndIncrementRefCounter, getFileScope } from './fileScope';
import { validateContract } from './validateContract';
import { getIdentOption } from './adapter';

export function createVar(debugId?: string): CSSVarFunction {
// Convert ref count to base 36 for optimal hash lengths
Expand All @@ -20,7 +21,7 @@ export function createVar(debugId?: string): CSSVarFunction {
packageName ? `${packageName}${filePath}` : filePath,
);
const varName =
process.env.NODE_ENV !== 'production' && debugId
getIdentOption() === 'debug' && debugId
? `${debugId}__${fileScopeHash}${refCount}`
: `${fileScopeHash}${refCount}`;

Expand Down
5 changes: 5 additions & 0 deletions packages/esbuild-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
getSourceFromVirtualCssFile,
compile,
vanillaExtractFilescopePlugin,
IdentifierOption,
} from '@vanilla-extract/integration';
import type { Plugin } from 'esbuild';

Expand All @@ -15,12 +16,14 @@ interface VanillaExtractPluginOptions {
externals?: Array<string>;
runtime?: boolean;
processCss?: (css: string) => Promise<string>;
identifiers?: IdentifierOption;
}
export function vanillaExtractPlugin({
outputCss,
externals = [],
runtime = false,
processCss,
identifiers,
}: VanillaExtractPluginOptions = {}): Plugin {
if (runtime) {
// If using runtime CSS then just apply fileScopes to code
Expand Down Expand Up @@ -64,6 +67,8 @@ export function vanillaExtractPlugin({
source,
filePath: path,
outputCss,
identOption:
identifiers ?? (build.initialOptions.minify ? 'short' : 'debug'),
});

return {
Expand Down
2 changes: 2 additions & 0 deletions packages/integration/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export { getPackageInfo } from './packageInfo';
export { compile, vanillaExtractFilescopePlugin } from './compile';
export { hash } from './hash';
export * from './filters';

export type { IdentifierOption } from './processVanillaFile';
5 changes: 5 additions & 0 deletions packages/integration/src/processVanillaFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@ function parseFileScope(serialisedFileScope: string): FileScope {
};
}

export type IdentifierOption = ReturnType<Adapter['getIdentOption']>;

interface ProcessVanillaFileOptions {
source: string;
filePath: string;
outputCss?: boolean;
identOption?: IdentifierOption;
serializeVirtualCssPath?: (file: {
fileName: string;
base64Source: string;
Expand All @@ -37,6 +40,7 @@ export function processVanillaFile({
source,
filePath,
outputCss = true,
identOption = process.env.NODE_ENV === 'production' ? 'short' : 'debug',
serializeVirtualCssPath,
}: ProcessVanillaFileOptions) {
type Css = Parameters<Adapter['appendCss']>[0];
Expand Down Expand Up @@ -68,6 +72,7 @@ export function processVanillaFile({
usedCompositions.add(identifier);
},
onEndFileScope: () => {},
getIdentOption: () => identOption,
};

setAdapter(cssAdapter);
Expand Down
8 changes: 8 additions & 0 deletions packages/snowpack-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ import {
processVanillaFile,
compile,
getSourceFromVirtualCssFile,
IdentifierOption,
} from '@vanilla-extract/integration';

interface Options {
identifiers?: IdentifierOption;
}
export default function vanillaExtractPlugin(
snowpackConfig: SnowpackConfig,
{ identifiers }: Options = {},
): SnowpackPlugin {
const importedByMap = new Map();

Expand Down Expand Up @@ -53,6 +58,9 @@ export default function vanillaExtractPlugin(
source,
filePath,
outputCss: !isSSR,
identOption:
identifiers ??
(snowpackConfig.mode === 'production' ? 'short' : 'debug'),
serializeVirtualCssPath({ base64Source, fileScope }) {
const cssUrl = `${path.join(cwd, fileScope.filePath)}.css`;

Expand Down
4 changes: 2 additions & 2 deletions packages/sprinkles/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
"author": "SEEK",
"license": "MIT",
"peerDependencies": {
"@vanilla-extract/css": "*"
"@vanilla-extract/css": "^1.0.0"
},
"devDependencies": {
"@vanilla-extract/css": "*"
"@vanilla-extract/css": "^1.0.0"
}
}
8 changes: 7 additions & 1 deletion packages/vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ import {
compile,
hash,
getPackageInfo,
IdentifierOption,
} from '@vanilla-extract/integration';

export function vanillaExtractPlugin(): Plugin {
interface Options {
identifiers?: IdentifierOption;
}
export function vanillaExtractPlugin({ identifiers }: Options = {}): Plugin {
let config: ResolvedConfig;
let packageInfo: ReturnType<typeof getPackageInfo>;
const cssMap = new Map<string, string>();
Expand Down Expand Up @@ -83,6 +87,8 @@ export function vanillaExtractPlugin(): Plugin {
source,
filePath: id,
outputCss: !ssr,
identOption:
identifiers ?? (config.mode === 'production' ? 'short' : 'debug'),
});
},
};
Expand Down
Loading