Configuration
WyW-in-JS can be customized using a JavaScript, JSON or YAML file. This can be in form of:
wyw-in-js.config.jsJS file exporting the object (recommended).wyw-in-jsproperty in apackage.jsonfile..wyw-in-jsrcfile with JSON or YAML syntax..wyw-in-jsrc.json,.wyw-in-jsrc.yaml,.wyw-in-jsrc.yml, or.wyw-in-jsrc.jsfile.
Example wyw-in-js.config.js:
module.exports = {
evaluate: true,
displayName: false,
};Options
-
evaluate: boolean(default:true):Controls static evaluation of template expressions during dependency collection. It does not disable module evaluation. If there is nothing to evaluate, WyW-in-JS skips evaluation regardless of this flag. The old behavior of
evaluate: false(throwing on unsupported interpolation) is deprecated and kept only for legacy configs. -
displayName: boolean(default:false):Enabling this will add a display name to generated class names, e.g.
.Title_abcdefinstead of `.abcdef'. It is disabled by default to generate smaller CSS files. -
variableNameConfig: "var" | "dashes" | "raw"(default:var):Configures how the variable will be formatted in final CSS.
Possible values
-
varUse full css variable structure. This is default behavior.
import { styled } from '@linaria/react'; export const MyComponent = styled.div` color: ${(props) => props.color}; `;In CSS you will see full variable declaration
.MyComponent_m1cus5as { color: var(--m1cus5as-0); } -
dashesRemoves
var()around the variable name. It is useful when you want to control the variable on your own. For example you can set default value for CSS variable.import { styled } from '@linaria/react'; export const Theme = styled.div` --font-color: red; `; export const MyComponent = styled.div` // Returning empty string is mandatory // Otherwise you will have "undefined" in css variable value color: var(${(props) => props.color ?? ''}, var(--font-color)); `; function App() { return ( <Theme> <MyComponent>Text with red color</MyComponent> <MyComponent color="blue">Text with blue color</MyComponent> </Theme> ); }In CSS you will see generated variable name and your default value.
.Theme_t1cus5as { --font-color: red; } .MyComponent_mc195ga { color: var(--mc195ga-0, var(--font-color)); } -
rawUse only variable name without dashes and
var()wrapper.import { styled } from '@linaria/react'; export const MyComponent = styled.div` color: ${(props) => props.color}; `;In CSS you will see just the variable name. This is not valid value for css property.
.MyComponent_mc195ga { color: mc195ga-0; }You will have to make it valid:
export const MyComponent = styled.div` color: var(--${(props) => props.color}); `;
-
-
classNameSlug: string | ((hash: string, title: string, args: ClassNameSlugVars) => string)(default:default):Using this will provide an interface to customize the output of the CSS class name. Example:
classNameSlug: '[title]',Would generate a class name such as
.headerinstead of the default.header_absdjfsdfwhich includes a hash.You may also use a function to define the slug. The function will be evaluated at build time and must return a string:
classNameSlug: (hash, title) => `${hash}__${7 * 6}__${title}`,Would generate the class name
.absdjfsdf__42__header.Last argument
argsis an object that contains following properties:title,hash,index,dir,ext,file,name. These properties are useful when you want to generate your own hash:const sha1 = require('sha1'); module.exports = { classNameSlug: (hash, title, args) => sha1(`${args.name}-${title}`), };note invalid characters will be replaced with an underscore (
_).Variables
hash: The hash of the content.title: The name of the class.
-
variableNameSlug: string | ((context: IVariableContext) => string)(default:default):Using this will provide an interface to customize the output of the CSS variable name. Example:
variableNameSlug: '[componentName]-[valueSlug]-[index]',Would generate a variable name such as
--Title-absdjfsdf-0instead of the@react/styled's default--absdjfsdf-0.You may also use a function to define the slug. The function will be evaluated at build time and must return a string:
variableNameSlug: (context) => `${context.valueSlug}__${context.componentName}__${context.precedingCss.match(/([\w-]+)\s*:\s*$/)[1]}`,Would generate the variable name
--absdjfsdf__Title__flex-direction.note invalid characters will be replaced with an underscore (
_).Variables
componentName- the displayName of the component.componentSlug- the component slug.index- the index of the css variable in the current component.precedingCss- the preceding part of the css for the variable, i.e.flex: 1; flex-direction:.processor- the processor used to process the tag (e.g. 'StyledProcessor' or 'AtomicStyledProcessor').source- the string source of the css property value.unit- the unit.valueSlug- the value slug.
-
overrideContext: (context: Partial<vm.Context>, filename: string) => Partial<vm.Context>A custom function to override the context used to evaluate modules. This can be used to add custom globals or override the default ones.
module.exports = { overrideContext: (context, filename) => ({ ...context, HighLevelAPI: () => "I'm a high level API", }), }; -
importOverrides: Record<string, { mock: string } | { noShake: true } | { unknown: "allow" | "warn" | "error" }>Overrides how imports are handled during prepare/eval stages.
-
Keys:
- File imports (raw specifier starts with
.) are keyed by a canonical root-relative path of the resolved file, e.g../src/foo.ts. - Package imports are keyed by the raw specifier as written in code, e.g.
reactor@scope/pkg.
- File imports (raw specifier starts with
-
Actions:
-
Each override value is one of:
mock: replace the resolved target for the import (rawsourcestays intact).noShake: disable tree-shaking for this import (forcesonly=['*']).unknown: controls behavior when an import reaches eval-time Node resolver fallback (warnby default).
-
Example:
module.exports = { importOverrides: { './src/i18n/messages/en.json': { unknown: 'allow' }, react: { mock: './src/__mocks__/react.ts' }, './src/vendor/broken-module.ts': { noShake: true }, }, };Notes:
- When WyW evaluates
__wywPreval, it tree-shakes the module and removesimport '...';side-effect imports by default, to avoid executing unrelated runtime code in Node.js (some libraries touchdocument,window, etc). - If you need a side-effect import to run during evaluation, or you need to stub a problematic side-effect import, add an override for that import:
{ noShake: true }keeps the import and disables tree-shaking for that dependency.{ mock: './path/to/mock' }keeps the import but redirects it to a mock module.
Example (stub a problematic side-effect import during evaluation):
module.exports = { importOverrides: { '@radix-ui/react-tooltip': { mock: './src/__mocks__/radix-tooltip.ts' }, }, }; -
-
importLoaders: Record<string, "raw" | "url" | ((context) => unknown) | false>Allows handling of import resource queries (e.g.
?raw,?url,?svgUse) during evaluation.Notes:
- This affects only the WyW evaluation sandbox (values returned from
require()/ dynamic import during build), not your bundler runtime behavior. - If multiple query keys are present, the first matching key is used.
- Set a loader to
falseto disable it.
Built-in loaders:
"raw": returns file contents as a string (utf-8)."url": returns a relative (POSIX) path to the resolved file from the importing file directory.
Example:
module.exports = { importLoaders: { // Disable defaults if you don't want them // raw: false, // url: false, // Custom loader key svgUse: (ctx) => ctx.toUrl(), }, }; - This affects only the WyW evaluation sandbox (values returned from
-
rules: EvalRule[]The set of rules that defines how the matched files will be transformed during the evaluation.
EvalRuleis an object with two fields:testis a regular expression or a function(path: string) => boolean;actionis anEvaluatorfunction,"ignore"or a name of the module that exportsEvaluatorfunction as a default export.
If
testis omitted, the rule is applicable for all the files.The last matched rule is used for transformation. If the last matched action for a file is
"ignore"the file will be evaluated as is, so that file must not contain any js code that cannot be executed in nodejs environment (it's usually true for any lib innode_modules).If you need to compile certain modules under
/node_modules/(which can be the case in monorepo projects), it's recommended to do it on a module by module basis for faster transforms, e.g.ignore: /node_modules[\/\\](?!some-module|other-module)/. Example is using Regular Expressions negative lookahead.The Information about
Evaluator, its default setting and custom implementations can be founded it evaluators section of How it works docsThe default setup is:
import { shaker } from '@wyw-in-js/transform'; [ { action: shaker, }, { test: /[\\/]node_modules[\\/]/, action: 'ignore', }, { test: (filename, code) => { if (!/[\\/]node_modules[\\/]/.test(filename)) { return false; } return /(?:^|\*\/|;|})\s*(?:export|import)[\s{]/m.test(code); }, action: shaker, }, ]; -
tagResolver: (source, tag) => stringA custom function to use when resolving template tags.
By default, linaria APIs like
cssandstyledmust be imported directly from the package – this is because babel needs to be able to recognize the API's to do static style extraction.tagResolverallowscssandstyledAPIs to be imported from other files too.tagResolvertakes the path for the source module (eg.@linaria/core) and the name of imported tag (eg.css), and returns the full path to the related processor. IftagResolverreturnsnull, the default tag processor will be used.For example, we can use this to map
@linaria/core,@linaria/reactor@linaria/atomicwhere we re-export the module.{ tagResolver: (source, tag) => { const pathToLocalFile = join(__dirname, './my-local-folder/linaria.js'); if (source === pathToLocalFile) { if (tag === 'css') { return require.resolve('@linaria/core/processors/css'); } if (tag === 'styled') { return require.resolve('@linaria/react/processors/styled'); } } return null; }; }We can then re-export and use linaria API's from
./my-local-folder:// my-file.js import { css, styled } from './my-local-folder/linaria'; export const MyComponent = styled.div` color: red; `; export default css` border: 1px solid black; `;// ./my-local-folder/core.js export * from '@linaria/core'; -
babelOptions: ObjectIf you need to specify custom babel configuration, you can pass them here. These babel options will be used by Linaria when parsing and evaluating modules.
-
features: Record<string, FeatureFlag>A map of feature flags to enable/disable. See Feature Flags for more information.
-
codeRemover: CodeRemoverOptionsAn object with two keys
componentTypesandhocs. Specifies types of variables and HOCs that will be replaced with an empty function before evaluation.{ codeRemover: { componentTypes: { react: ['FC', 'FunctionComponent', 'ExoticComponent'], preact: ['FunctionComponent'], }, hocs: { redux: ['connect'], }, }, }
@wyw-in-js/babel-preset
The preset pre-processes and evaluates the CSS. The bundler plugins use this preset under the hood. You also might want to use this preset if you import the components outside of the files handled by your bundler, such as on your server or in unit tests.
To use this preset, add @wyw-in-js/babel-preset to your Babel configuration at the end of the presets list:
.babelrc:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react",
+ "@wyw-in-js"
]
}The babel preset can accept the same options supported by the configuration file, however it's recommended to use the configuration file directly.