facebook / facebook/stylex

Destructuring of `stylex.env` properties

Open
#1,541 0 comments 1 reaction 0 assignees View on GitHub
bug
Dominant language
JavaScript
Stars
10.3k
Forks
481
Avg merge
3d 8h
Merged PRs (30d)
13

Description

### Describe the issue

I'm not sure if this is a bug or just something that was never implemented, but trying to destructure `stylex.env` throws an error.

Even with intenseness, it is cumbersome to repeatedly type `env.theme.colors.primary100`. Being able to access colors directly would make the workflow of using `env` a lot more convenient.

### Expected behavior

I'd expect this to work

```ts
import * as stylex from '@stylexjs/stylex';
const { colors } = stylex.env;

export const styles = stylex.create({
root: {
color: colors.brand,
},
});
```

### Steps to reproduce

*version:* 18.1
*package:* @stylexjs/stylex

With the following babel.config.js:
```js
module.exports = {
plugins: [
['@stylexjs/babel-plugin', {
env: {
tokens: {
colors: {
brand: '#0066ff',
},
spacing: {
small: '4px',
medium: '8px',
large: '16px',
},
},
},
}],
],
};
```

The code in "expected behavior", this error is thrown:

```sh
● @stylexjs/babel-plugin › [transform] stylex.create() › static styles › stylex.env resolves compile-time constants

SyntaxError: unknown file: Unsupported expression: VariableDeclarator

1 |
2 | import * as stylex from '@stylexjs/stylex';
> 3 | const { colors } = stylex.env;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4 | export const styles = stylex.create({
5 | root: {
6 | color: colors.brand,

218 |
219 | if (!confident) {
> 220 | throw (deopt ?? path).buildCodeFrameError(
| ^
221 | reason ?? messages.nonStaticValue('create'),
222 | SyntaxError,
223 | );

at File.buildCodeFrameError (../../../node_modules/@babel/core/src/transformation/file/file.ts:251:12)
at NodePath.buildError [as buildCodeFrameError] (../../../node_modules/@babel/traverse/src/path/index.ts:161:21)
at buildCodeFrameError (src/visitors/stylex-create.js:220:29)
at PluginPass.CallExpression (src/index.js:362:30)
at call (../../../node_modules/@babel/traverse/src/visitors.ts:299:14)

```

### Test case

```js
test('stylex.env resolves compile-time constants with destructuring', () => {
const { code, metadata } = transform(
`
import * as stylex from '@stylexjs/stylex';
const { brandPrimary } = stylex.env;
export const styles = stylex.create({
root: {
color: brandPrimary,
}
});
`,
{ env: { brandPrimary: '#123456' } },
);
expect(code).toMatchInlineSnapshot(`
"import * as stylex from '@stylexjs/stylex';
export const styles = {
root: {
kMwMTN: "x1tfn4g9",
$$css: true
}
};"
`);
expect(metadata).toMatchInlineSnapshot(`
{
"stylex": [
[
"x1tfn4g9",
{
"ltr": ".x1tfn4g9{color:#123456}",
"rtl": null,
},
3000,
],
],
}
`);
});
```

### Additional comments

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.