@salty-css/webpack 0.0.1-alpha.30 → 0.0.1-alpha.300

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,15 +1,458 @@
1
- # Salty Css
1
+ ![Salty CSS Banner](https://salty-css.dev/assets/banners/dvd.svg)
2
2
 
3
- ## Basic usage example with Button
3
+ # Salty CSS - CSS-in-JS library that is kinda sweet
4
4
 
5
- ### Initial requirements
5
+ Is there anything saltier than CSS in frontend web development? Salty CSS is built to provide better developer experience for developers looking for performant and feature rich CSS-in-JS solutions.
6
6
 
7
- 1. Add `saltyPlugin` to vite or webpack config from `@salty-css/vite` or `@salty-css/webpack`
8
- 2. Create `salty.config.ts` to the root of your project
9
- 3. Import global styles to any regular .css file from `saltygen/index.css` (does not exist during first run, cli command coming later)
10
- 4. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
7
+ [Get started](#get-started) | [API](#api) | [Discord](https://discord.gg/R6kr4KxMhP) | [Website](https://salty-css.dev/) | [GitHub](https://github.com/margarita-form/salty-css) | [NPM](https://www.npmjs.com/package/@salty-css/core)
11
8
 
12
- ### Code examples
9
+ ## Features
10
+
11
+ - Build time compilation to achieve awesome runtime performance and minimal size
12
+ - Next.js, React Server Components, Astro, Vite and Webpack support
13
+ - Type safety with out of the box TypeScript and ESLint plugin
14
+ - Advanced CSS variables configuration to allow smooth token usage
15
+ - Style templates to create reusable styles easily
16
+
17
+ ## Get started
18
+
19
+ Fastest way to get started with any framework is
20
+
21
+ ```bash
22
+ npx salty-css init
23
+ ```
24
+
25
+ Other guides:
26
+
27
+ - Next.js → [Next.js guide](#nextjs) + [Next.js example app](https://github.com/margarita-form/salty-css-website)
28
+ - React + Vite → [React + Vite guide](#react--vite) + [React example code](#code-examples)
29
+ - React + Webpack → Guide coming soon
30
+
31
+ ## Useful commands
32
+
33
+ - Create component: `npx salty-css generate [filePath]`
34
+ - Build: `npx salty-css build [directory]`
35
+ - Update Salty CSS packages: `npx salty-css up`
36
+
37
+ ## Good to know
38
+
39
+ 1. All Salty CSS functions (`styled`, `classNames`, `keyframes`, etc.) must be created in `*.css.ts` or `*.css.tsx` files. This is to ensure best build performance.
40
+ 2. Salty CSS components created with styled function can extend non Salty CSS components (`export const CustomLink = styled(NextJSLink, { ... });`) but those components must take in `className` prop for styles to apply.
41
+ 3. Among common types like `string` and `number`, CSS-in-JS properties in Salty CSS do support `functions` and `promises` as values (`styled('span', { base: { color: async () => 'red' } });`) but running asynchronous tasks or importing heavy 3rd party libraries into `*.css.ts` or `*.css.tsx` files can cause longer build times.
42
+
43
+ ## Get support
44
+
45
+ To get help with problems, [Join Salty CSS Discord server](https://discord.gg/R6kr4KxMhP).
46
+
47
+ ## API
48
+
49
+ ### Component styling
50
+
51
+ - [styled](#styled-function) (react only) - create React components that can be used anywhere easily
52
+ - [className](#class-name-function) (framework agnostic) - create a CSS class string that can be applied to any element
53
+
54
+ ### Global styling
55
+
56
+ - [defineGlobalStyles](#global-styles) - set global styles like `html` and `body`
57
+ - [defineVariables](#variables) - create CSS variables (tokens) that can be used in any styling function
58
+ - [defineMediaQuery](#media-queries) - create CSS media queries and use them in any styling function
59
+ - [defineTemplates](#templates) - create reusable templates that can be applied when same styles are used over and over again
60
+ - [keyframes](#keyframes-animations) - create CSS keyframes animation that can be used and imported in any styling function
61
+
62
+ ### Styling helpers & utility
63
+
64
+ - [defineViewportClamp](#viewport-clamp) - create CSS clamp functions that are based on user's viewport and can calculate relative values easily
65
+ - [color](#color-function) - transform any valid color code or variable to be darker, lighter etc. easily (uses [color library by Qix-](https://github.com/Qix-/color))
66
+
67
+ ### Salty CSS CLI
68
+
69
+ In your existing repository you can use `npx salty-css [command]` to initialize a project, generate components, update related packages and build required files.
70
+
71
+ - Initialize project → `npx salty-css init [directory]` - Installs required packages, detects framework in use and creates project files to the provided directory. Directory can be left blank if you want files to be created to the current directory.
72
+ - Generate component → `npx salty-css update [version]` - Update @salty-css packages in your repository. Default version is "latest". Additional options like `--dir`, `--tag`, `--name` and `--className` are also supported.
73
+ - Build files → `npx salty-css build [directory/filename]` - Compile Salty CSS related files in your project. This should not be needed if you are using tools like Next.js or Vite
74
+
75
+ ## Styled function
76
+
77
+ Styled function is the main way to use Salty CSS within React. Styled function creates a React component that then can be used anywhere in your app. All styled functions must be created in `.css.ts` or `.css.tsx` files
78
+
79
+ ```ts
80
+ // /components/my-component.css.ts
81
+ import { styled } from '@salty-css/react/styled';
82
+
83
+ // Define a component with a styled function. First argument is the component name or existing component to extend and second argument is the object containing the styles and other options
84
+ export const Component = styled('div', {
85
+ className: 'wrapper', // Define optional custom class name that will be included for this component
86
+ element: 'section', // Override the html element that will be rendered for this component
87
+ base: {
88
+ // 👉 Add your CSS-in-JS base styles here! 👈
89
+ },
90
+ variants: {
91
+ // Define conditional styles that will be applied to the component based on the variant prop values
92
+ },
93
+ compoundVariants: [
94
+ // Define conditional styles that will be applied to the component based on the combination of variant prop values
95
+ ],
96
+ defaultVariants: {
97
+ // Set default variant prop values
98
+ },
99
+ defaultProps: {
100
+ // Add additional default props for the component (eg, id and other html element attributes)
101
+ },
102
+ passProps: true, // Pass variant props to the rendered element / parent component (default: false)
103
+ priority: 1, // Override automatic priotity layer with a custom value (0-8), higher is considered more important
104
+ });
105
+ ```
106
+
107
+ Example usage:
108
+
109
+ ```tsx
110
+ import { Component } from './my-component.css';
111
+
112
+ export const Page = () => {
113
+ return <Component>Hello world</Component>;
114
+ };
115
+ ```
116
+
117
+ ## Class name function
118
+
119
+ Create CSS class names with possibility to add scope and media queries etc. Function `className` is quite similar to `styled` but does not allow extending components or classes.
120
+
121
+ ```ts
122
+ // /components/my-class.css.ts
123
+ import { className } from '@salty-css/react/class-name';
124
+
125
+ // Define a CSS class with className function. First and only argument is the object containing the styles and other options
126
+ export const myClass = className({
127
+ className: 'wrapper', // Define optional custom class name that will be included to the scope
128
+ base: {
129
+ // 👉 Add your CSS-in-JS base styles here! 👈
130
+ },
131
+ });
132
+ ```
133
+
134
+ Example usage:
135
+
136
+ ```tsx
137
+ import { myClass } from './my-class.css';
138
+
139
+ export const Page = () => {
140
+ return <div className={myClass}>Hello world</div>;
141
+ };
142
+ ```
143
+
144
+ ## Global styles
145
+
146
+ ```ts
147
+ // /styles/global.css.ts
148
+ import { defineGlobalStyles } from '@salty-css/core/factories';
149
+
150
+ export default defineGlobalStyles({
151
+ html: {
152
+ fontFamily: 'Arial, sans-serif',
153
+ },
154
+ body: {
155
+ backgroundColor: '#fff',
156
+ margin: 0,
157
+ },
158
+ // Add more global styles as needed
159
+ });
160
+ ```
161
+
162
+ ## Variables
163
+
164
+ ```ts
165
+ // /styles/variables.css.ts
166
+ import { defineVariables } from '@salty-css/core/factories';
167
+
168
+ export default defineVariables({
169
+ /*
170
+ Define static variable token (like colors, font sizes, etc.). and use them in your styles (e.g. color: '{colors.brand.highlight}').
171
+ Variables can be nested (colors.brand.main) and can reference other variables.
172
+ */
173
+ colors: {
174
+ dark: '#111',
175
+ light: '#fefefe',
176
+ brand: {
177
+ main: '#0070f3',
178
+ highlight: '#ff4081',
179
+ },
180
+ },
181
+ fontFamily: {
182
+ heading: 'Arial, sans-serif',
183
+ body: 'Georgia, serif',
184
+ },
185
+
186
+ /*
187
+ Define variables that are responsive to a media query (defined in media.css.ts) asn use them in your styles as normal (e.g. font-size: '{fontSize.heading.regular}').
188
+ These variables will be automatically updated when the media query is matched. Base values are used when no media query is matched.
189
+ */
190
+ responsive: {
191
+ base: {
192
+ fontSize: {
193
+ heading: {
194
+ small: '32px',
195
+ regular: '48px',
196
+ large: '64px',
197
+ },
198
+ body: {
199
+ small: '16px',
200
+ regular: '20px',
201
+ large: '24px',
202
+ },
203
+ },
204
+ },
205
+ '@largeMobileDown': {
206
+ fontSize: {
207
+ heading: {
208
+ small: '20px',
209
+ regular: '32px',
210
+ large: '48px',
211
+ },
212
+ body: {
213
+ small: '14px',
214
+ regular: '16px',
215
+ large: '20px',
216
+ },
217
+ },
218
+ },
219
+ },
220
+
221
+ /*
222
+ Conditional variables are used to define styles that depend on a class name (e.g. <div className="theme-dark">). or data-attribute (e.g. <div data-theme="dark">). Names for these variables will be "{theme.backgroundColor}" and "{theme.textColor}".
223
+ */
224
+ conditional: {
225
+ theme: {
226
+ dark: {
227
+ backgroundColor: '{colors.dark}',
228
+ textColor: '{colors.light}',
229
+ },
230
+ light: {
231
+ backgroundColor: '{colors.light}',
232
+ textColor: '{colors.dark}',
233
+ },
234
+ },
235
+ },
236
+ });
237
+ ```
238
+
239
+ Example usage:
240
+
241
+ ```ts
242
+ styled('span', {
243
+ base: {
244
+ // Use of static font family variable
245
+ fontFamily: '{fontFamily.heading}',
246
+ // Use of responsive font size variable
247
+ fontSize: '{fontSize.heading.regular}',
248
+ // Use of conditional theme text color variable
249
+ color: '{theme.textColor}',
250
+ },
251
+ });
252
+ ```
253
+
254
+ ## Media queries
255
+
256
+ Create global media queries that can be either used directly as a scope (e.g. `'@MEDIA_QUERY_NAME': { color: 'blue' }`) or imported to be used in JS.
257
+
258
+ ```ts
259
+ // /styles/media.css.ts
260
+ import { defineMediaQuery } from '@salty-css/react/config';
261
+
262
+ export const largePortraitUp = defineMediaQuery((media) => media.minWidth(600));
263
+ export const largeMobileDown = defineMediaQuery((media) => media.maxWidth(600));
264
+ ```
265
+
266
+ Example usage:
267
+
268
+ ```ts
269
+ styled('span', { base: { fontSize: '64px', '@largeMobileDown': { fontSize: '32px' } } });
270
+ ```
271
+
272
+ ## Templates
273
+
274
+ With templates you can create reusable styles that can be used in any styles function. Templates can be static (all values defined in the template) or functions (parameters can be passed to define values). Templates can be used in styles by using template's name (e.g. textStyle) as property name and for static a key as the value for functions any supported parameter value can be used as the value.
275
+
276
+ ```ts
277
+ // /styles/templates.css.ts
278
+ import { defineTemplates } from '@salty-css/core/factories';
279
+
280
+ export default defineTemplates({
281
+ // Static templates for text styles.
282
+ textStyle: {
283
+ headline: {
284
+ small: {
285
+ fontSize: '{fontSize.heading.small}',
286
+ },
287
+ regular: {
288
+ fontSize: '{fontSize.heading.regular}',
289
+ },
290
+ large: {
291
+ fontSize: '{fontSize.heading.large}',
292
+ },
293
+ },
294
+ body: {
295
+ small: {
296
+ fontSize: '{fontSize.body.small}',
297
+ lineHeight: '1.5em',
298
+ },
299
+ regular: {
300
+ fontSize: '{fontSize.body.regular}',
301
+ lineHeight: '1.33em',
302
+ },
303
+ },
304
+ },
305
+ // Dynamic function templates for card styles.
306
+ card: (value: string) => {
307
+ return {
308
+ padding: value,
309
+ borderRadius: '8px',
310
+ boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)',
311
+ };
312
+ },
313
+ });
314
+ ```
315
+
316
+ Example usage:
317
+
318
+ ```ts
319
+ styled('div', { base: { textStyle: 'headline.large', card: '20px' } });
320
+ ```
321
+
322
+ ## Keyframes animations
323
+
324
+ ```ts
325
+ // /styles/animations.css.ts
326
+ import { keyframes } from '@salty-css/react/keyframes';
327
+
328
+ export const fadeIn = keyframes({
329
+ // Name of the animation in final CSS
330
+ animationName: 'fadeIn',
331
+ // Add `from` or `0%` to the component's css making it the initial state.
332
+ appendInitialStyles: true,
333
+ // CSS animation default params used with the value
334
+ params: {
335
+ delay: '250ms',
336
+ fillMode: 'forwards',
337
+ },
338
+ // Rest is animation timeline
339
+ from: {
340
+ opacity: 0,
341
+ },
342
+ to: {
343
+ opacity: 1,
344
+ },
345
+ });
346
+ ```
347
+
348
+ Example usage:
349
+
350
+ ```ts
351
+ import { fadeIn } from 'path-to-animations.css.ts';
352
+
353
+ export const Wrapper = styled('div', { base: { animation: fadeIn } });
354
+ ```
355
+
356
+ ## Viewport clamp
357
+
358
+ Create a CSS clamp function based on screen sizes. Useful when aiming to create font sizes or spacings that scale with the screen.
359
+
360
+ ```ts
361
+ // /styles/clamp.css.ts
362
+ import { defineViewportClamp } from '@salty-css/react/helpers';
363
+
364
+ export const fhdClamp = defineViewportClamp({ screenSize: 1920 });
365
+ export const mobileClamp = defineViewportClamp({ screenSize: 640 });
366
+ ```
367
+
368
+ Example usage:
369
+
370
+ ```ts
371
+ styled('span', { base: { fontSize: fhdClamp(96), '@largeMobileDown': { fontSize: mobileClamp(48) } } });
372
+ ```
373
+
374
+ ## Color function
375
+
376
+ Modify any color easily, add opacity, darken...
377
+
378
+ Example usage:
379
+
380
+ ```ts
381
+ import { color } from '@salty-css/core/helpers';
382
+
383
+ export const Wrapper = styled('span', { base: { backgroundColor: color('#000').alpha(0.5) } });
384
+ ```
385
+
386
+ ## Usage
387
+
388
+ ### Next.js
389
+
390
+ ![salty-next](https://github.com/user-attachments/assets/2cf6a93f-cdd5-4f5f-ab2e-3bc8bcfb83e8)
391
+
392
+ Salty CSS provides Next.js App & Pages router support with full React Server Components support.
393
+
394
+ ### Add Salty CSS to Next.js
395
+
396
+ 1. In your existing Next.js repository you can run `npx salty-css init` to automatically configure Salty CSS.
397
+ 2. Create your first Salty CSS component with `npx salty-css generate [filePath]` (e.g. src/custom-wrapper)
398
+ 3. Import your component for example to `page.tsx` and see it working!
399
+
400
+ And note: steps 2 & 3 are just to show how get new components up and running, step 1 does all of the important stuff 🤯
401
+
402
+ #### Manual configuration
403
+
404
+ 1. For Next.js support install `npm i @salty-css/next @salty-css/core @salty-css/react`
405
+ 2. Create `salty.config.ts` to your app directory
406
+ 3. Add Salty CSS plugin to next.js config
407
+
408
+ - **Next.js 15:** In `next.config.ts` add import for salty plugin `import { withSaltyCss } from '@salty-css/next';` and then add `withSaltyCss` to wrap your nextConfig export like so `export default withSaltyCss(nextConfig);`
409
+ - **Next.js 14 and older:** In `next.config.js` add import for salty plugin `const { withSaltyCss } = require('@salty-css/next');` and then add `withSaltyCss` to wrap your nextConfig export like so `module.exports = withSaltyCss(nextConfig);`
410
+
411
+ 4. Make sure that `salty.config.ts` and `next.config.ts` are in the same folder!
412
+ 5. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
413
+ 6. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
414
+
415
+ [Check out Next.js demo project](https://github.com/margarita-form/salty-css-website) or [react example code](#code-examples)
416
+
417
+ ---
418
+
419
+ ### React + Vite
420
+
421
+ ![salty-vite-react](https://github.com/user-attachments/assets/12ec5b6a-0dcc-48fa-afc1-d337fc8f800c)
422
+
423
+ ### Add Salty CSS to your React + Vite app
424
+
425
+ 1. In your existing Vite repository you can run `npx salty-css init` to automatically configure Salty CSS.
426
+ 2. Create your first Salty CSS component with `npx salty-css generate [filePath]` (e.g. src/custom-wrapper)
427
+ 3. Import your component for example to `main.tsx` and see it working!
428
+
429
+ And note: steps 2 & 3 are just to show how get new components up and running, step 1 does all of the important stuff 🤯
430
+
431
+ ### Test it out
432
+
433
+ Check out React + Vite + Salty CSS demo repository at https://github.com/margarita-form/salty-css-react-vite-demo or view it in CodeSandbox:
434
+
435
+ [![Edit margarita-form/salty-css-react-vite-demo/main](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/p/github/margarita-form/salty-css-react-vite-demo/main?import=true&embed=1)
436
+
437
+ ### Manual configuration
438
+
439
+ 1. For Vite support install `npm i @salty-css/vite @salty-css/core`
440
+ 2. In `vite.config` add import for salty plugin `import { saltyPlugin } from '@salty-css/vite';` and then add `saltyPlugin(__dirname)` to your vite configuration plugins
441
+ 3. Make sure that `salty.config.ts` and `vite.config.ts` are in the same folder!
442
+ 4. Build `saltygen` directory by running your app once or with cli `npx salty-css build [directory]`
443
+ 5. Import global styles from `saltygen/index.css` to some global css file with `@import 'insert_path_to_index_css';`.
444
+
445
+ [Check out react example code](#code-examples)
446
+
447
+ ---
448
+
449
+ ### Create components
450
+
451
+ 1. Create salty components with styled only inside files that end with `.css.ts`, `.salty.ts` `.styled.ts` or `.styles.ts`
452
+
453
+ ## Code examples
454
+
455
+ ### Basic usage example with Button
13
456
 
14
457
  **Salty config**
15
458
 
@@ -31,23 +474,6 @@ export const config = defineConfig({
31
474
  });
32
475
  ```
33
476
 
34
- **Your React component file**
35
-
36
- ```tsx
37
- import { Wrapper } from '../components/wrapper/wrapper.css';
38
- import { Button } from '../components/button/button.css';
39
-
40
- export const IndexPage = () => {
41
- return (
42
- <Wrapper>
43
- <Button variant="solid" onClick={() => alert('It is a button.')}>
44
- Outlined
45
- </Button>
46
- </Wrapper>
47
- );
48
- };
49
- ```
50
-
51
477
  **Wrapper** (`components/wrapper/wrapper.css.ts`)
52
478
 
53
479
  ```tsx
@@ -72,7 +498,7 @@ export const Button = styled('button', {
72
498
  padding: `0.6em 1.2em`,
73
499
  border: '1px solid currentColor',
74
500
  background: 'transparent',
75
- color: 'currentColor/40',
501
+ color: 'currentColor',
76
502
  cursor: 'pointer',
77
503
  transition: '200ms',
78
504
  textDecoration: 'none',
@@ -108,4 +534,21 @@ export const Button = styled('button', {
108
534
  });
109
535
  ```
110
536
 
537
+ **Your React component file**
538
+
539
+ ```tsx
540
+ import { Wrapper } from '../components/wrapper/wrapper.css';
541
+ import { Button } from '../components/button/button.css';
542
+
543
+ export const IndexPage = () => {
544
+ return (
545
+ <Wrapper>
546
+ <Button variant="solid" onClick={() => alert('It is a button.')}>
547
+ Outlined
548
+ </Button>
549
+ </Wrapper>
550
+ );
551
+ };
552
+ ```
553
+
111
554
  More examples coming soon
package/index.cjs CHANGED
@@ -1,15 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("path"),I=require("esbuild"),W=require("child_process"),m=require("fs");require("fs/promises");function H(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(s,e,n.get?n:{enumerable:!0,get:()=>t[e]})}}return s.default=t,Object.freeze(s)}const x=H(I),E=t=>String.fromCharCode(t+(t>25?39:97)),z=(t,s)=>{let e="",n;for(n=Math.abs(t);n>52;n=n/52|0)e=E(n%52)+e;return e=E(n%52)+e,e.length<s?e=e.padStart(s,"a"):e.length>s&&(e=e.slice(-s)),e},B=(t,s)=>{let e=s.length;for(;e;)t=t*33^s.charCodeAt(--e);return t},A=(t,s=3)=>{const e=B(5381,JSON.stringify(t))>>>0;return z(e,s)};function V(t){return t?typeof t!="string"?V(String(t)):t.replace(/\s/g,"-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g,(s,e)=>(e>0?"-":"")+s.toLowerCase()):""}const G=(t,s)=>{if(typeof t!="string")return{result:t};if(!s)return{result:t};const e=[];return Object.values(s).forEach(n=>{const{pattern:r,transform:a}=n;t=t.replace(r,b=>{const{value:l,css:$}=a(b);return $&&e.push($),l})}),{result:t,additionalCss:e}},M=t=>typeof t!="string"?{result:t}:/\{[^{}]+\}/g.test(t)?{result:t.replace(/\{([^{}]+)\}/g,(...n)=>`var(--${V(n[1].replaceAll(".","-"))})`)}:{result:t},k=(t,s,e,n)=>{if(!t)return"";const r=[],a=Object.entries(t).reduce((l,[$,o])=>{const y=$.trim();if(typeof o=="function"&&(o=o()),typeof o=="object"){if(!o)return l;if(y==="variants")return Object.entries(o).forEach(([f,i])=>{i&&Object.entries(i).forEach(([p,c])=>{if(!c)return;const h=`${s}.${f}-${p}`,S=k(c,h);r.push(S)})}),l;if(y==="defaultVariants")return l;if(y==="compoundVariants")return o.forEach(f=>{const{css:i,...p}=f,c=Object.entries(p).reduce((S,[P,T])=>`${S}.${P}-${T}`,s),h=k(i,c);r.push(h)}),l;if(y.startsWith("@")){const f=k(o,s),i=`${y} {
2
- ${f.replace(`
3
- `,`
4
- `)}
5
- }`;return r.push(i),l}const j=$.includes("&")?y.replace("&",s):y.startsWith(":")?`${s}${y}`:`${s} ${y}`,d=k(o,j);return r.push(d),l}const g=y.startsWith("-")?y:V(y),w=(j,d=";")=>l=`${l}${j}${d}`,O=j=>w(`${g}:${j}`);if(typeof o=="number")return O(o);if(typeof o!="string")if("toString"in o)o=o.toString();else return l;const{modifiers:C}={},D=function*(){yield M(o),yield G(o,C)}();for(const{result:j,additionalCss:d=[]}of D)o=j,d.forEach(f=>{const i=k(f,"");w(i,"")});return O(o)},"");if(!a)return r.join(`
6
- `);if(!s)return a;let b="";return b=`${s} { ${a} }`,[b,...r].join(`
7
- `)},_=(t,s=[])=>{if(!t)return"";const e=[],n={};if(Object.entries(t).forEach(([r,a])=>{if(typeof a=="object"){if(!a)return;const b=r.trim(),l=_(a,[...s,b]);e.push(l)}else n[r]=a}),Object.keys(n).length){const r=s.map(V).join("-"),a=k(n,`.${r}`);e.push(a)}return e.join(`
8
- `)},N=t=>u.join(t,"./saltygen"),J=["salty","css","styles","styled"],q=(t=[])=>new RegExp(`\\.(${[...J,...t].join("|")})\\.`),K=(t,s=[])=>q(s).test(t),L=async t=>{const s=N(t),e=u.join(t,"salty.config.ts"),n=u.join(s,"salty.config.js");await x.build({entryPoints:[e],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",external:["react"]});const r=Date.now(),{config:a}=await import(`${n}?t=${r}`);return a},U=async t=>{const s=await L(t),e=new Set,n=(f,i=[])=>f?Object.entries(f).flatMap(([p,c])=>{if(!c)return;if(typeof c=="object")return n(c,[...i,p]);const h=[...i,p].join(".");e.add(`"${h}"`);const S=[...i.map(V),V(p)].join("-"),{result:P}=M(c);return`--${S}: ${P};`}):[],r=f=>f?Object.entries(f).flatMap(([i,p])=>{const c=n(p);return i==="base"?c.join(""):`${i} { ${c.join("")} }`}):[],a=f=>f?Object.entries(f).flatMap(([i,p])=>Object.entries(p).flatMap(([c,h])=>{const S=n(h,[i]),P=`.${i}-${c}, [data-${i}="${c}"]`,T=S.join("");return`${P} { ${T} }`})):[],b=n(s.variables),l=r(s.responsiveVariables),$=a(s.conditionalVariables),o=N(t),y=u.join(o,"css/variables.css"),g=`:root { ${b.join("")} ${l.join("")} } ${$.join("")}`;m.writeFileSync(y,g);const w=u.join(o,"types/css-tokens.d.ts"),C=`type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;m.writeFileSync(w,C);const F=u.join(o,"css/global.css"),D=k(s.global,"");m.writeFileSync(F,D);const j=u.join(o,"css/templates.css"),d=_(s.templates);m.writeFileSync(j,d)},X=async(t,s)=>{const e=A(t),n=u.join(s,"js",e+".js");await x.build({entryPoints:[t],minify:!0,treeShaking:!0,bundle:!0,outfile:n,format:"esm",target:["es2022"],keepNames:!0,external:["react"]});const r=Date.now();return await import(`${n}?t=${r}`)},Y=async t=>{const s=N(t),e=u.join(s,"salty.config.js"),{config:n}=await import(e);return n},Q=async t=>{try{const s=[],e=[],n=N(t),r=u.join(n,"index.css");(()=>{m.existsSync(n)&&W.execSync("rm -rf "+n),m.mkdirSync(n),m.mkdirSync(u.join(n,"css")),m.mkdirSync(u.join(n,"types"))})(),await U(t);const b=await Y(t);async function l(g,w){const O=m.statSync(g);if(O.isDirectory()){const C=m.readdirSync(g);await Promise.all(C.map(F=>l(u.join(g,F),u.join(w,F))))}else if(O.isFile()&&K(g)){const F=await X(g,n),D=[];Object.entries(F).forEach(([i,p])=>{if(p.isKeyframes&&p.css){const T=`${p.animationName}.css`,Z=`css/${T}`,R=u.join(n,Z);s.push(T),m.writeFileSync(R,p.css);return}if(!p.generator)return;const c=p.generator._withBuildContext({name:i,config:b}),h=`${c.hash}-${c.priority}.css`;e[c.priority]||(e[c.priority]=[]),e[c.priority].push(h),D.push(h);const S=`css/${h}`,P=u.join(n,S);m.writeFileSync(P,c.css)});const j=D.map(i=>`@import url('./${i}');`).join(`
9
- `),d=A(g,6),f=u.join(n,`css/${d}.css`);m.writeFileSync(f,j)}}await l(t,n);const $=s.map(g=>`@import url('./css/${g}');`).join(`
10
- `);let y=`@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
11
-
12
- ${["@import url('./css/variables.css');","@import url('./css/global.css');","@import url('./css/templates.css');"].join(`
13
- `)}
14
- ${$}`;if(b.importStrategy!=="component"){const g=e.flat().map(w=>`@import url('./css/${w}');`).join(`
15
- `);y+=g}m.writeFileSync(r,y)}catch(s){console.error(s)}},v=(t,s)=>{var e,n,r;(n=(e=t.module)==null?void 0:e.rules)==null||n.push({test:q(),use:[{loader:u.resolve("./loader.js"),options:{dir:s}}]}),(r=t.plugins)==null||r.push({apply:a=>{a.hooks.afterPlugins.tap({name:"generateCss"},async()=>{await Q(s)})}})};exports.saltyPlugin=v;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const f=require("path"),s=require("@salty-css/core/compiler"),y=require("@salty-css/core/server"),d=require("fs"),i=(a,e,n=!1,c=!1)=>{var l,r,o;(r=(l=a.module)==null?void 0:l.rules)==null||r.push({test:s.saltyFileRegExp(),use:[{loader:f.resolve(__dirname,c?"./loader.cjs":"./loader.js"),options:{dir:e}}]}),n||(o=a.plugins)==null||o.push({apply:p=>{let u=!1;p.hooks.beforeCompile.tapPromise({name:"generateCss"},async()=>{u||(u=!0,await s.generateCss(e),d.watch(e,{recursive:!0},async(g,t)=>{await y.checkShouldRestart(t)?await s.generateCss(e,!1,!1):s.isSaltyFile(t)&&await s.generateFile(e,t)}))})}})};exports.default=i;exports.saltyPlugin=i;
package/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  import { Configuration } from 'webpack';
2
- export declare const saltyPlugin: (config: Configuration, dir: string) => void;
2
+ export declare const saltyPlugin: (config: Configuration, dir: string, isServer?: boolean, cjs?: boolean) => void;
3
+ export default saltyPlugin;
package/index.js CHANGED
@@ -1,225 +1,29 @@
1
- import { join as m, resolve as H } from "path";
2
- import * as A from "esbuild";
3
- import { execSync as q } from "child_process";
4
- import { existsSync as B, mkdirSync as x, statSync as G, readdirSync as J, writeFileSync as w } from "fs";
5
- import "fs/promises";
6
- const E = (t) => String.fromCharCode(t + (t > 25 ? 39 : 97)), K = (t, s) => {
7
- let e = "", n;
8
- for (n = Math.abs(t); n > 52; n = n / 52 | 0) e = E(n % 52) + e;
9
- return e = E(n % 52) + e, e.length < s ? e = e.padStart(s, "a") : e.length > s && (e = e.slice(-s)), e;
10
- }, L = (t, s) => {
11
- let e = s.length;
12
- for (; e; ) t = t * 33 ^ s.charCodeAt(--e);
13
- return t;
14
- }, M = (t, s = 3) => {
15
- const e = L(5381, JSON.stringify(t)) >>> 0;
16
- return K(e, s);
17
- };
18
- function T(t) {
19
- return t ? typeof t != "string" ? T(String(t)) : t.replace(/\s/g, "-").replace(/[A-Z](?:(?=[^A-Z])|[A-Z]*(?=[A-Z][^A-Z]|$))/g, (s, e) => (e > 0 ? "-" : "") + s.toLowerCase()) : "";
20
- }
21
- const z = (t, s) => {
22
- if (typeof t != "string") return { result: t };
23
- if (!s) return { result: t };
24
- const e = [];
25
- return Object.values(s).forEach((n) => {
26
- const { pattern: r, transform: a } = n;
27
- t = t.replace(r, (g) => {
28
- const { value: l, css: b } = a(g);
29
- return b && e.push(b), l;
30
- });
31
- }), { result: t, additionalCss: e };
32
- }, Z = (t) => typeof t != "string" ? { result: t } : /\{[^{}]+\}/g.test(t) ? { result: t.replace(/\{([^{}]+)\}/g, (...n) => `var(--${T(n[1].replaceAll(".", "-"))})`) } : { result: t }, k = (t, s, e, n) => {
33
- if (!t) return "";
34
- const r = [], a = Object.entries(t).reduce((l, [b, o]) => {
35
- const u = b.trim();
36
- if (typeof o == "function" && (o = o()), typeof o == "object") {
37
- if (!o) return l;
38
- if (u === "variants")
39
- return Object.entries(o).forEach(([f, i]) => {
40
- i && Object.entries(i).forEach(([p, c]) => {
41
- if (!c) return;
42
- const h = `${s}.${f}-${p}`, j = k(c, h);
43
- r.push(j);
44
- });
45
- }), l;
46
- if (u === "defaultVariants")
47
- return l;
48
- if (u === "compoundVariants")
49
- return o.forEach((f) => {
50
- const { css: i, ...p } = f, c = Object.entries(p).reduce((j, [C, O]) => `${j}.${C}-${O}`, s), h = k(i, c);
51
- r.push(h);
52
- }), l;
53
- if (u.startsWith("@")) {
54
- const f = k(o, s), i = `${u} {
55
- ${f.replace(`
56
- `, `
57
- `)}
58
- }`;
59
- return r.push(i), l;
60
- }
61
- const $ = b.includes("&") ? u.replace("&", s) : u.startsWith(":") ? `${s}${u}` : `${s} ${u}`, d = k(o, $);
62
- return r.push(d), l;
63
- }
64
- const y = u.startsWith("-") ? u : T(u), S = ($, d = ";") => l = `${l}${$}${d}`, D = ($) => S(`${y}:${$}`);
65
- if (typeof o == "number") return D(o);
66
- if (typeof o != "string")
67
- if ("toString" in o) o = o.toString();
68
- else return l;
69
- const { modifiers: F } = {}, V = function* () {
70
- yield Z(o), yield z(o, F);
71
- }();
72
- for (const { result: $, additionalCss: d = [] } of V)
73
- o = $, d.forEach((f) => {
74
- const i = k(f, "");
75
- S(i, "");
76
- });
77
- return D(o);
78
- }, "");
79
- if (!a) return r.join(`
80
- `);
81
- if (!s) return a;
82
- let g = "";
83
- return g = `${s} { ${a} }`, [g, ...r].join(`
84
- `);
85
- }, R = (t, s = []) => {
86
- if (!t) return "";
87
- const e = [], n = {};
88
- if (Object.entries(t).forEach(([r, a]) => {
89
- if (typeof a == "object") {
90
- if (!a) return;
91
- const g = r.trim(), l = R(a, [...s, g]);
92
- e.push(l);
93
- } else
94
- n[r] = a;
95
- }), Object.keys(n).length) {
96
- const r = s.map(T).join("-"), a = k(n, `.${r}`);
97
- e.push(a);
98
- }
99
- return e.join(`
100
- `);
101
- }, N = (t) => m(t, "./saltygen"), U = ["salty", "css", "styles", "styled"], I = (t = []) => new RegExp(`\\.(${[...U, ...t].join("|")})\\.`), X = (t, s = []) => I(s).test(t), Y = async (t) => {
102
- const s = N(t), e = m(t, "salty.config.ts"), n = m(s, "salty.config.js");
103
- await A.build({
104
- entryPoints: [e],
105
- minify: !0,
106
- treeShaking: !0,
107
- bundle: !0,
108
- outfile: n,
109
- format: "esm",
110
- external: ["react"]
111
- });
112
- const r = Date.now(), { config: a } = await import(`${n}?t=${r}`);
113
- return a;
114
- }, Q = async (t) => {
115
- const s = await Y(t), e = /* @__PURE__ */ new Set(), n = (f, i = []) => f ? Object.entries(f).flatMap(([p, c]) => {
116
- if (!c) return;
117
- if (typeof c == "object") return n(c, [...i, p]);
118
- const h = [...i, p].join(".");
119
- e.add(`"${h}"`);
120
- const j = [...i.map(T), T(p)].join("-"), { result: C } = Z(c);
121
- return `--${j}: ${C};`;
122
- }) : [], r = (f) => f ? Object.entries(f).flatMap(([i, p]) => {
123
- const c = n(p);
124
- return i === "base" ? c.join("") : `${i} { ${c.join("")} }`;
125
- }) : [], a = (f) => f ? Object.entries(f).flatMap(([i, p]) => Object.entries(p).flatMap(([c, h]) => {
126
- const j = n(h, [i]), C = `.${i}-${c}, [data-${i}="${c}"]`, O = j.join("");
127
- return `${C} { ${O} }`;
128
- })) : [], g = n(s.variables), l = r(s.responsiveVariables), b = a(s.conditionalVariables), o = N(t), u = m(o, "css/variables.css"), y = `:root { ${g.join("")} ${l.join("")} } ${b.join("")}`;
129
- w(u, y);
130
- const S = m(o, "types/css-tokens.d.ts"), F = `type VariableTokens = ${[...e].join("|")}; type PropertyValueToken = \`{\${VariableTokens}}\``;
131
- w(S, F);
132
- const P = m(o, "css/global.css"), V = k(s.global, "");
133
- w(P, V);
134
- const $ = m(o, "css/templates.css"), d = R(s.templates);
135
- w($, d);
136
- }, v = async (t, s) => {
137
- const e = M(t), n = m(s, "js", e + ".js");
138
- await A.build({
139
- entryPoints: [t],
140
- minify: !0,
141
- treeShaking: !0,
142
- bundle: !0,
143
- outfile: n,
144
- format: "esm",
145
- target: ["es2022"],
146
- keepNames: !0,
147
- external: ["react"]
148
- });
149
- const r = Date.now();
150
- return await import(`${n}?t=${r}`);
151
- }, tt = async (t) => {
152
- const s = N(t), e = m(s, "salty.config.js"), { config: n } = await import(e);
153
- return n;
154
- }, st = async (t) => {
155
- try {
156
- const s = [], e = [], n = N(t), r = m(n, "index.css");
157
- (() => {
158
- B(n) && q("rm -rf " + n), x(n), x(m(n, "css")), x(m(n, "types"));
159
- })(), await Q(t);
160
- const g = await tt(t);
161
- async function l(y, S) {
162
- const D = G(y);
163
- if (D.isDirectory()) {
164
- const F = J(y);
165
- await Promise.all(F.map((P) => l(m(y, P), m(S, P))));
166
- } else if (D.isFile() && X(y)) {
167
- const P = await v(y, n), V = [];
168
- Object.entries(P).forEach(([i, p]) => {
169
- if (p.isKeyframes && p.css) {
170
- const O = `${p.animationName}.css`, W = `css/${O}`, _ = m(n, W);
171
- s.push(O), w(_, p.css);
172
- return;
173
- }
174
- if (!p.generator) return;
175
- const c = p.generator._withBuildContext({
176
- name: i,
177
- config: g
178
- }), h = `${c.hash}-${c.priority}.css`;
179
- e[c.priority] || (e[c.priority] = []), e[c.priority].push(h), V.push(h);
180
- const j = `css/${h}`, C = m(n, j);
181
- w(C, c.css);
182
- });
183
- const $ = V.map((i) => `@import url('./${i}');`).join(`
184
- `), d = M(y, 6), f = m(n, `css/${d}.css`);
185
- w(f, $);
186
- }
187
- }
188
- await l(t, n);
189
- const b = s.map((y) => `@import url('./css/${y}');`).join(`
190
- `);
191
- let u = `@layer l0, l1, l2, l3, l4, l5, l6, l7, l8;
192
-
193
- ${["@import url('./css/variables.css');", "@import url('./css/global.css');", "@import url('./css/templates.css');"].join(`
194
- `)}
195
- ${b}`;
196
- if (g.importStrategy !== "component") {
197
- const y = e.flat().map((S) => `@import url('./css/${S}');`).join(`
198
- `);
199
- u += y;
200
- }
201
- w(r, u);
202
- } catch (s) {
203
- console.error(s);
204
- }
205
- }, it = (t, s) => {
206
- var e, n, r;
207
- (n = (e = t.module) == null ? void 0 : e.rules) == null || n.push({
208
- test: I(),
1
+ import { resolve as m } from "path";
2
+ import { saltyFileRegExp as f, generateCss as i, isSaltyFile as c, generateFile as y } from "@salty-css/core/compiler";
3
+ import { checkShouldRestart as d } from "@salty-css/core/server";
4
+ import { watch as h } from "fs";
5
+ const k = (t, e, u = !1, n = !1) => {
6
+ var a, l, o;
7
+ (l = (a = t.module) == null ? void 0 : a.rules) == null || l.push({
8
+ test: f(),
209
9
  use: [
210
10
  {
211
- loader: H("./loader.js"),
212
- options: { dir: s }
11
+ loader: m(__dirname, n ? "./loader.cjs" : "./loader.js"),
12
+ options: { dir: e }
213
13
  }
214
14
  ]
215
- }), (r = t.plugins) == null || r.push({
216
- apply: (a) => {
217
- a.hooks.afterPlugins.tap({ name: "generateCss" }, async () => {
218
- await st(s);
15
+ }), u || (o = t.plugins) == null || o.push({
16
+ apply: (p) => {
17
+ let r = !1;
18
+ p.hooks.beforeCompile.tapPromise({ name: "generateCss" }, async () => {
19
+ r || (r = !0, await i(e), h(e, { recursive: !0 }, async (g, s) => {
20
+ await d(s) ? await i(e, !1, !1) : c(s) && await y(e, s);
21
+ }));
219
22
  });
220
23
  }
221
24
  });
222
25
  };
223
26
  export {
224
- it as saltyPlugin
27
+ k as default,
28
+ k as saltyPlugin
225
29
  };
package/loader.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";const i=require("@salty-css/core/compiler");async function r(){const{dir:e}=this.getOptions(),{resourcePath:t}=this;return await i.generateFile(e,t),await i.minimizeFile(e,t)}module.exports=r;
package/loader.js ADDED
@@ -0,0 +1,8 @@
1
+ import { generateFile as i, minimizeFile as a } from "@salty-css/core/compiler";
2
+ async function n() {
3
+ const { dir: t } = this.getOptions(), { resourcePath: e } = this;
4
+ return await i(t, e), await a(t, e);
5
+ }
6
+ export {
7
+ n as default
8
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salty-css/webpack",
3
- "version": "0.0.1-alpha.30",
3
+ "version": "0.0.1-alpha.300",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.mjs",
6
6
  "typings": "./dist/index.d.ts",
@@ -10,7 +10,12 @@
10
10
  "publishConfig": {
11
11
  "access": "public"
12
12
  },
13
- "homepage": "https://github.com/margarita-form/salty-css",
13
+ "description": "Webpack plugin for Salty CSS",
14
+ "homepage": "https://salty-css.dev/",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/margarita-form/salty-css.git"
18
+ },
14
19
  "bugs": {
15
20
  "url": "https://github.com/margarita-form/salty-css/issues"
16
21
  },
@@ -29,7 +34,7 @@
29
34
  }
30
35
  },
31
36
  "dependencies": {
32
- "@salty-css/core": "^0.0.1-alpha.30",
37
+ "@salty-css/core": "^0.0.1-alpha.300",
33
38
  "webpack": ">=5.x"
34
39
  }
35
40
  }