Skip to content

Commit

Permalink
Support identifier formatting configuration (#323)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcompiles authored Aug 27, 2021
1 parent 26832f1 commit 1e7d647
Show file tree
Hide file tree
Showing 25 changed files with 407 additions and 231 deletions.
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/).

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
20 changes: 20 additions & 0 deletions 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 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
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

0 comments on commit 1e7d647

Please sign in to comment.