@adamlui/scss-to-css 1.5.2 → 1.6.1

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,10 +1,26 @@
1
- # { } scss-to-css.js
1
+ <div align="right">
2
+ <h6>
3
+ <picture>
4
+ <source type="image/svg+xml" media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/white/icon32.svg">
5
+ <img height=14 src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/black/icon32.svg">
6
+ </picture>
7
+ &nbsp;English |
8
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/zh-cn#readme">简体中文</a> |
9
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/zh-tw#readme">繁體中文</a> |
10
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/hi#readme">हिंदी</a> |
11
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/bn#readme">বাংলা</a> |
12
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/mr#readme">मराठी</a> |
13
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/pa#readme">ਪੰਜਾਬੀ</a>
14
+ </h6>
15
+ </div>
16
+
17
+ # { } scss-to-css
2
18
 
3
19
  ### Recursively compile all SCSS files into minified CSS.
4
20
 
5
21
  <a href="https://www.npmjs.com/package/@adamlui/scss-to-css"><img height=31 src="https://img.shields.io/npm/dt/%40adamlui%2Fscss-to-css?logo=npm&logoColor=white&labelColor=464646&style=for-the-badge"></a>
6
22
  <a href="#%EF%B8%8F-mit-license"><img height=31 src="https://img.shields.io/badge/License-MIT-red.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
7
- <a href="https://www.npmjs.com/package/@adamlui/scss-to-css?activeTab=versions"><img height=31 src="https://img.shields.io/badge/Latest_Build-1.5.2-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
23
+ <a href="https://www.npmjs.com/package/@adamlui/scss-to-css?activeTab=versions"><img height=31 src="https://img.shields.io/badge/Latest_Build-1.6.1-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
8
24
  <a href="https://www.npmjs.com/package/@adamlui/scss-to-css?activeTab=code"><img height=31 src="https://img.shields.io/npm/unpacked-size/%40adamlui%2Fscss-to-css?style=for-the-badge&logo=ebox&logoColor=white&color=blue&labelColor=464646"></a>
9
25
  <a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:scss-to-css/scss-to-css.js"><img height=31 src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dadamlui_js-utils%3Ascss-to-css%2Fscss-to-css.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold"></a>
10
26
 
@@ -18,13 +34,19 @@ As a **global utility**:
18
34
  npm install -g @adamlui/scss-to-css
19
35
  ```
20
36
 
21
- As a **dev dependency**, from your project root:
37
+ As a **dev dependency** (e.g. for build scripts), from your project root:
22
38
 
23
39
  ```
24
40
  npm install -D @adamlui/scss-to-css
25
41
  ```
26
42
 
27
- ## 💻 Usage
43
+ As a **runtime dependency** (e.g. for on-the-fly compilation), from your project root:
44
+
45
+ ```
46
+ npm install @adamlui/scss-to-css
47
+ ```
48
+
49
+ ## 💻 Command line usage
28
50
 
29
51
  The basic **global command** is:
30
52
 
@@ -32,8 +54,6 @@ The basic **global command** is:
32
54
  scss-to-css
33
55
  ```
34
56
 
35
- **💡 Note:** Pass `-n` or `--dry-run` to only see what files will be processed.
36
-
37
57
  Sample output:
38
58
 
39
59
  <img src="https://github.com/adamlui/js-utils/blob/main/scss-to-css/media/images/sample-output.png">
@@ -48,10 +68,10 @@ To specify **input/output** paths:
48
68
  scss-to-css [input_path] [output_path]
49
69
  ```
50
70
 
51
- - `[input_path]`: Path to SCSS file or directory containing SCSS files to be compiled, relative to the current working directory.
52
- - `[output_path]`: Path to file or directory where CSS + sourcemap files will be stored, relative to original file location (if not provided, `css/` is used).
71
+ - `[input_path]`: Path to SCSS file or directory containing SCSS files to be compiled, relative to the current working directory.
72
+ - `[output_path]`: Path to file or directory where CSS + source map files will be stored, relative to original file location (if not provided, `css/` is used).
53
73
 
54
- **💡 Note:** If folders are passed, files will be processed recursively unless `-R` or `--no-recursion` is passed. To include dotfolders, pass `-d` or `--include-dotfolders`.
74
+ **💡 Note:** If folders are passed, files will be processed recursively unless `-R` or `--no-recursion` is passed.
55
75
 
56
76
  #
57
77
 
@@ -66,6 +86,35 @@ To use as a **package script**, in your project's `package.json`:
66
86
  Replace `<scss-to-css-cmd>` with `scss-to-css` + optional args. Then, `npm run build:css` can be used to run the command.
67
87
  <br><br>
68
88
 
89
+ ### Example commands
90
+
91
+ Compile all SCSS files in the **current directory** (outputs to `css/`):
92
+
93
+ ```
94
+ scss-to-css
95
+ ```
96
+
97
+ Compile all SCSS files in a **specific directory** (outputs to `path/to/your/directory/css/`):
98
+
99
+ ```
100
+ scss-to-css path/to/your/directory
101
+ ```
102
+
103
+ Compile a **specific file** (outputs to `path/to/your/css/file.min.css`):
104
+
105
+ ```
106
+ scss-to-css path/to/your/file.scss
107
+ ```
108
+
109
+ Specify both **input and output** directories (outputs to `output_folder/`):
110
+
111
+ ```
112
+ scss-to-css input_folder output_folder
113
+ ```
114
+
115
+ **💡 Note:** Output CSS is minified unless `-M` or `--no-minify` is passed.
116
+ <br><br>
117
+
69
118
  ### Command line options
70
119
 
71
120
  ```
@@ -83,34 +132,82 @@ Info commands:
83
132
  -v, --version Show version number.
84
133
  ```
85
134
 
86
- ### Example commands
135
+ ## 🔌 API reference
87
136
 
88
- Compile all SCSS files in the **current directory** (outputs to `css/`):
137
+ You can also import **scss-to-css** into your app to use its API methods, both as an ECMAScript module or a CommonJS module.
138
+
139
+ #### ESM:
89
140
 
141
+ ```js
142
+ import * as scssToCSS from '@adamlui/scss-to-css';
90
143
  ```
91
- scss-to-css
144
+
145
+ #### CJS:
146
+
147
+ ```js
148
+ const scssToCSS = require('@adamlui/scss-to-css');
92
149
  ```
93
150
 
94
- Compile all SCSS files in a **specific directory** (outputs to `path/to/your/directory/css/`):
151
+ ### compile(inputPath, options)
152
+
153
+ This function compiles SCSS found in the `inputPath` provided into CSS data.
154
+
155
+ If a **file path** is passed, the file's code is compiled to CSS, then an object containing `srcPath` + `code` + `error` is returned:
95
156
 
157
+ ```js
158
+ const compileResult = scssToCSS.compile('assets/style.scss');
159
+ console.log(compileResult.error); // runtime error, or `undefined` if no error
160
+ console.log(compileResult.code); // compiled CSS output of assets/style.scss
96
161
  ```
97
- scss-to-css path/to/your/directory
162
+
163
+ If a **directory path** is passed, SCSS files are searched for (recursively by default), each one's code is loaded then compiled, then an array of objects containing `srcPath` + `code` + `error` is returned:
164
+
165
+ ```js
166
+ const results = scssToCSS.compile('.');
167
+ results.forEach(result =>
168
+ console.log(result.srcPath)); // paths to SCSS files in working directory + all nested directories
169
+ console.log(results[1].code); // compiled CSS output of 2nd SCSS file if found, or `undefined` if not found
98
170
  ```
99
171
 
100
- Compile a **specific file** (outputs to `path/to/your/css/file.min.css`):
172
+ Options are boolean, passed as object properties. For example:
101
173
 
174
+ ```js
175
+ scssToCSS.compile(inputDir, { minify: false });
176
+ // returns data objects where `.code` contains unminified CSS
102
177
  ```
103
- scss-to-css path/to/your/file.scss
178
+
179
+ Possible parameters (and their default settings) are:
180
+
181
+ ```
182
+ recursive (true) Recursively search for nested files if dir path
183
+ passed.
184
+ verbose (true) Show logging in console/terminal.
185
+ dotFolders (false) Include dotfolders in file search.
186
+ minify (true) Minify output CSS.
187
+ sourceMaps (true) Generate CSS source maps.
104
188
  ```
105
189
 
106
- Specify both **input and output** directories (outputs to `output_folder/`):
190
+ ### findSCSS(searchDir, options)
191
+
192
+ This function searches for all SCSS files within the `searchDir` string passed (useful for discovering what files [`compile()`](#compileinputpath-options) will process) and returns an array containing their filepaths.
193
+
194
+ Options are boolean, passed as object properties. For example:
107
195
 
196
+ ```js
197
+ scssToCSS.findSCSS(searchDir, { recursive: false });
198
+ // returns array containing filepaths to SCSS files in exactly `searchDir`
108
199
  ```
109
- scss-to-css input_folder output_folder
200
+
201
+ Possible parameters (and their default settings) are:
202
+
203
+ ```
204
+ recursive (true) Recursively search for nested files if dir path
205
+ passed.
206
+ verbose (false) Show logging in console/terminal.
207
+ dotFolders (false) Include dotfolders in file search.
110
208
  ```
111
209
 
112
- **💡 Note:** Output CSS is minified unless `-M` or `--no-minify` is passed.
113
- <br><br>
210
+ <br>
114
211
 
115
212
  ## 💖 Support
116
213
 
@@ -119,7 +216,7 @@ Please consider [giving a GitHub ⭐](https://github.com/adamlui/js-utils) if th
119
216
 
120
217
  ## 🏛️ MIT License
121
218
 
122
- **Copyright (c) 2024 [Adam Lui](https://github.com/adamlui)**
219
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui) & contributors**
123
220
 
124
221
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
125
222
 
@@ -133,4 +230,4 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
133
230
 
134
231
  <a href="https://github.com/adamlui/js-utils">**Home**</a> /
135
232
  <a href="https://github.com/adamlui/js-utils/discussions">Discuss</a> /
136
- <a href="#--scss-to-cssjs">Back to top ↑</a>
233
+ <a href="#--scss-to-css">Back to top ↑</a>
package/docs/LICENSE.md CHANGED
@@ -1,9 +1,25 @@
1
- # 🏛️ MIT License
2
-
3
- **Copyright (c) 2024 [Adam Lui](https://github.com/adamlui)**
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1
+ <div align="right">
2
+ <h6>
3
+ <picture>
4
+ <source type="image/svg+xml" media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/white/icon32.svg">
5
+ <img height=14 src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/black/icon32.svg">
6
+ </picture>
7
+ &nbsp;English |
8
+ <a href="zh-cn/LICENSE.md">简体中文</a> |
9
+ <a href="zh-tw/LICENSE.md">繁體中文</a> |
10
+ <a href="hi/LICENSE.md">हिंदी</a> |
11
+ <a href="bn/LICENSE.md">বাংলা</a> |
12
+ <a href="mr/LICENSE.md">मराठी</a> |
13
+ <a href="pa/LICENSE.md">ਪੰਜਾਬੀ</a>
14
+ </h6>
15
+ </div>
16
+
17
+ # 🏛️ MIT License
18
+
19
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui) & contributors**
20
+
21
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
22
+
23
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/docs/SECURITY.md CHANGED
@@ -1,5 +1,21 @@
1
- # 🛡️ Security Policy
2
-
3
- If you find a vulnerability, please open a [draft security advisory](https://github.com/adamlui/js-utils/security/advisories/new).
4
-
5
- Pull requests are also welcome, but for safety reasons, send an email to <adam@kudoai.com> and wait for a response before making it public.
1
+ <div align="right">
2
+ <h6>
3
+ <picture>
4
+ <source type="image/svg+xml" media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/white/icon32.svg">
5
+ <img height=14 src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/black/icon32.svg">
6
+ </picture>
7
+ &nbsp;English |
8
+ <a href="zh-cn/SECURITY.md">简体中文</a> |
9
+ <a href="zh-tw/SECURITY.md">繁體中文</a> |
10
+ <a href="hi/SECURITY.md">हिंदी</a> |
11
+ <a href="bn/SECURITY.md">বাংলা</a> |
12
+ <a href="mr/SECURITY.md">मराठी</a> |
13
+ <a href="pa/SECURITY.md">ਪੰਜਾਬੀ</a>
14
+ </h6>
15
+ </div>
16
+
17
+ # 🛡️ Security Policy
18
+
19
+ If you find a vulnerability, please open a [draft security advisory](https://github.com/adamlui/js-utils/security/advisories/new).
20
+
21
+ Pull requests are also welcome, but for safety reasons, send an email to <adam@kudoai.com> and wait for a response before making it public.
package/package.json CHANGED
@@ -1,48 +1,50 @@
1
- {
2
- "name": "@adamlui/scss-to-css",
3
- "version": "1.5.2",
4
- "description": "Recursively compile all SCSS files into minified CSS",
5
- "author": {
6
- "name": "Adam Lui",
7
- "email": "adam@kudoai.com",
8
- "url": "https://github.com/adamlui"
9
- },
10
- "homepage": "https://github.com/adamlui/js-utils",
11
- "license": "MIT",
12
- "main": "scss-to-css.js",
13
- "bin": {
14
- "scsstocss": "scss-to-css.js",
15
- "scss-to-css": "scss-to-css.js"
16
- },
17
- "scripts": {
18
- "test": "echo \"Error: no test specified\" && exit 1",
19
- "bump:patch": "bash utils/bump.sh patch",
20
- "bump:minor": "bash utils/bump.sh minor",
21
- "bump:major": "bash utils/bump.sh major",
22
- "publish:patch": "bash utils/bump.sh patch --publish",
23
- "publish:minor": "bash utils/bump.sh minor --publish",
24
- "publish:major": "bash utils/bump.sh major --publish"
25
- },
26
- "repository": {
27
- "type": "git",
28
- "url": "git+https://github.com/adamlui/js-utils.git"
29
- },
30
- "keywords": [
31
- "scss",
32
- "sass",
33
- "css",
34
- "stylesheets",
35
- "compiler",
36
- "minifier"
37
- ],
38
- "bugs": {
39
- "url": "https://github.com/adamlui/js-utils/issues"
40
- },
41
- "dependencies": {
42
- "sass": "^1.71.1"
43
- },
44
- "funding": {
45
- "type": "github",
46
- "url": "https://github.com/sponsors/adamlui"
47
- }
48
- }
1
+ {
2
+ "name": "@adamlui/scss-to-css",
3
+ "version": "1.6.1",
4
+ "description": "Recursively compile all SCSS files into minified CSS",
5
+ "author": {
6
+ "name": "Adam Lui",
7
+ "email": "adam@kudoai.com",
8
+ "url": "https://github.com/adamlui"
9
+ },
10
+ "homepage": "https://github.com/adamlui/js-utils",
11
+ "license": "MIT",
12
+ "main": "scss-to-css.js",
13
+ "bin": {
14
+ "scsstocss": "scss-to-css.js",
15
+ "scss-to-css": "scss-to-css.js"
16
+ },
17
+ "scripts": {
18
+ "test": "echo \"Error: no test specified\" && exit 1",
19
+ "bump:patch": "bash utils/bump.sh patch",
20
+ "bump:minor": "bash utils/bump.sh minor",
21
+ "bump:major": "bash utils/bump.sh major",
22
+ "publish:patch": "bash utils/bump.sh patch --publish",
23
+ "publish:minor": "bash utils/bump.sh minor --publish",
24
+ "publish:major": "bash utils/bump.sh major --publish"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/adamlui/js-utils.git"
29
+ },
30
+ "keywords": [
31
+ "scss",
32
+ "compiler",
33
+ "minifier",
34
+ "cli",
35
+ "api",
36
+ "sass",
37
+ "css",
38
+ "stylesheets"
39
+ ],
40
+ "bugs": {
41
+ "url": "https://github.com/adamlui/js-utils/issues"
42
+ },
43
+ "dependencies": {
44
+ "sass": "^1.72.0"
45
+ },
46
+ "funding": {
47
+ "type": "github",
48
+ "url": "https://github.com/sponsors/adamlui"
49
+ }
50
+ }
package/scss-to-css.js CHANGED
@@ -1,162 +1,209 @@
1
- #!/usr/bin/env node
2
-
3
- // Import LIBS
4
- const fs = require('fs'),
5
- path = require('path'),
6
- sass = require('sass');
7
-
8
- // Init UI colors
9
- const nc = '\x1b[0m', // no color
10
- br = '\x1b[1;91m', // bright red
11
- by = '\x1b[1;33m', // bright yellow
12
- bg = '\x1b[1;92m'; // bright green
13
-
14
- // Load FLAG settings
15
- const config = {
16
- dryRun: process.argv.some(arg => /^--?(?:n|dry-?run)$/.test(arg)),
17
- includeDotFolders: process.argv.some(arg =>
18
- /^--?(?:dd?|(?:include-?)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?)$/.test(arg)),
19
- disableSourceMaps: process.argv.some(arg =>
20
- /^--?(?:S|(?:exclude|disable|no)-?so?u?rce?-?maps?)$/.test(arg)),
21
- noRecursion: process.argv.some(arg =>
22
- /^--?(?:R|(?:disable|no)-?recursion)$/.test(arg)),
23
- noMinify: process.argv.some(arg =>
24
- /^--?(?:M|(?:disable|no)-?minif(?:y|ication))$/.test(arg)),
25
- quietMode: process.argv.some(arg => /^--?q(?:uiet)?$/.test(arg))
26
- };
27
-
28
- // Show HELP screen if -h or --help passed
29
- if (process.argv.some(arg => /^--?h(?:elp)?$/.test(arg))) {
30
-
31
- printHelp(`\n${by}scss-to-css [inputPath] [outputPath] [options]${nc}`);
32
- printHelp('\nPath arguments:');
33
- printHelp(' [inputPath] '
34
- + 'Path to SCSS file or directory containing SCSS files to be compiled,'
35
- + ' relative to the current working directory.');
36
- printHelp(' [outputPath] '
37
- + 'Path to file or directory where CSS + sourcemap files will be stored,'
38
- + ' relative to original file location (if not provided, css/ is used).');
39
- printHelp('\nConfig options:');
40
- printHelp(' -n, --dry-run Don\'t actually compile the file(s),'
41
- + ' just show if they will be processed.');
42
- printHelp(' -d, --include-dotfolders Include dotfolders in file search.');
43
- printHelp(' -S, --no-source-maps Prevent source maps from being generated.');
44
- printHelp(' -M, --no-minify Disable minification of output CSS.');
45
- printHelp(' -R, --no-recursion Disable recursive file searching.');
46
- printHelp(' -q, --quiet Suppress all logging except errors.');
47
- printHelp('\nInfo commands:');
48
- printHelp(' -h, --help Display this help screen.');
49
- printHelp(' -v, --version Show version number.');
50
-
51
- // Show VERSION number if -v or --version passed
52
- } else if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
53
- console.info('v' + require('./package.json').version);
54
-
55
- } else { // run MAIN routine
56
-
57
- // Init I/O args
58
- const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
59
- process.argv.slice(2) // exclude executable and script paths
60
- .filter(arg => !arg.startsWith('-')) // exclude flags
61
- .map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
62
- );
63
-
64
- // Validate input arg (output arg can be anything)
65
- const inputPath = path.resolve(process.cwd(), inputArg);
66
- if (inputArg && !fs.existsSync(inputPath)) {
67
- console.error(`\n${br}Error: First arg must be an existing file or directory.`
68
- + `\n${ inputPath } does not exist.${nc}`
69
- + `\n\n${bg}Example valid command: \n>> scss-to-css . output.min.css${nc}`
70
- + `\n\n${by}For all command options: \n>> scss-to-css --help${nc}`);
71
- process.exit(1);
72
- }
73
-
74
- // Find all eligible SCSS files or arg-passed file
75
- const scssFiles = [];
76
- if (inputArg.endsWith('.scss')) scssFiles.push(inputPath);
77
- else (function findSCSSfiles(dir) {
78
- const files = fs.readdirSync(dir);
79
- files.forEach(file => {
80
- const filePath = path.resolve(dir, file);
81
- if (fs.statSync(filePath).isDirectory() &&
82
- (config.includeDotFolders || !file.startsWith('.')) && !config.noRecursion)
83
- findSCSSfiles(filePath); // recursively find SCSS in eligible dir
84
- else if (file.endsWith('.scss')) // SCSS file found
85
- scssFiles.push(filePath); // store it for compilation
86
- });
87
- })(inputPath);
88
-
89
- if (scssFiles.length === 0) { // print nothing found
90
- printIfNotQuiet(`\n${by}No SCSS files found.${nc}`);
91
-
92
- } else if (config.dryRun) { // print files to be processed
93
- console.info(`\n${by}SCSS files to be compiled:${nc}`);
94
- scssFiles.forEach(file => console.info(file));
95
-
96
- } else { // actually compile SCSS files
97
-
98
- let cssGenCnt = 0, srcMapGenCnt = 0;
99
- printIfNotQuiet(''); // line break before first log
100
- scssFiles.forEach(scssPath => {
101
- printIfNotQuiet(`Compiling ${ scssPath }...`);
102
- try { // to compile SCSS file
103
- const outputDir = path.join(
104
- path.dirname(scssPath), // path of file to be minified
105
- /(?:src|s[ac]ss)$/.test(path.dirname(scssPath)) ? '../css' // + ../css/ if in *(src|sass|scss)/
106
- : outputArg.endsWith('.css') ? path.dirname(outputArg) // or path from file output arg
107
- : outputArg || 'css' // or path from folder output arg or css/ if no output arg passed
108
- );
109
- const outputFilename = (
110
- outputArg.endsWith('.css') && inputArg.endsWith('.scss')
111
- ? path.basename(outputArg).replace(/(\.min)?\.css$/, '')
112
- : path.basename(scssPath, '.scss')
113
- ) + '.min.css';
114
- const outputPath = path.join(outputDir, outputFilename),
115
- compileResult = sass.compile(scssPath, {
116
- style: config.noMinify ? 'expanded' : 'compressed',
117
- sourceMap: !config.disableSourceMaps });
118
- if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
119
- fs.writeFileSync(outputPath, compileResult.css, 'utf8'); cssGenCnt++;
120
- if (!config.disableSourceMaps) {
121
- fs.writeFileSync(outputPath + '.map', JSON.stringify(compileResult.sourceMap), 'utf8');
122
- srcMapGenCnt++;
123
- }
124
- } catch (err) { console.error(`${br}Error compiling ${ scssPath }: ${ err.message }${nc}`); }
125
- });
126
-
127
- // Print final summary
128
- if (cssGenCnt) {
129
- printIfNotQuiet(`\n${bg}Compilation complete!${nc}`);
130
- printIfNotQuiet(`${ cssGenCnt } CSS file${ cssGenCnt > 1 ? 's' : '' }`
131
- + ( srcMapGenCnt ? ` + ${ srcMapGenCnt } source map${ srcMapGenCnt > 1 ? 's' : '' }` : '' )
132
- + ' generated.');
133
- } else printIfNotQuiet(`${by}No SCSS files processed successfully.${nc}`);
134
- }
135
- }
136
-
137
- // Define LOGGING functions
138
-
139
- function printHelp(msg) { // wrap msg + indent 2nd+ lines (for --help screen)
140
- const terminalWidth = process.stdout.columns || 80,
141
- indentation = 30, lines = [], words = msg.match(/\S+|\s+/g);
142
-
143
- // Split msg into lines of appropriate lengths
144
- let currentLine = '';
145
- words.forEach(word => {
146
- const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
147
- if (currentLine.length + word.length > lineLength) { // cap/store it
148
- lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
149
- currentLine = '';
150
- }
151
- currentLine += word;
152
- });
153
- lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
154
-
155
- // Print formatted msg
156
- lines.forEach((line, index) => console.info(
157
- index === 0 ? line // print 1st line unindented
158
- : ' '.repeat(indentation) + line // print subsequent lines indented
159
- ));
160
- }
161
-
162
- function printIfNotQuiet(msg) { if (!config.quietMode) console.info(msg); }
1
+ #!/usr/bin/env node
2
+
3
+ // Import LIBS
4
+ const fs = require('fs'),
5
+ path = require('path'),
6
+ sass = require('sass');
7
+
8
+ // Define MAIN functions
9
+
10
+ function findSCSS(searchDir, options = {}) {
11
+ const defaultOptions = { recursive: true, verbose: false, dotFolders: false };
12
+ options = { ...defaultOptions, ...options };
13
+ const dirFiles = fs.readdirSync(searchDir), scssFiles = [];
14
+ dirFiles.forEach(file => {
15
+ const filePath = path.resolve(searchDir, file);
16
+ if (fs.statSync(filePath).isDirectory() && file != 'node_modules'
17
+ && (options.dotFolders || !file.startsWith('.')) && options.recursive) {
18
+ if (options.verbose) console.info(`Searching for SCSS files in: ${filePath}...`);
19
+ scssFiles.push( // recursively find SCSS in eligible dir
20
+ ...findSCSS(filePath, { ...options, isRecursing: true }));
21
+ } else if (file.endsWith('.scss')) // SCSS file found
22
+ scssFiles.push(filePath); // store it for compilation
23
+ });
24
+ if (options.isRecursing || scssFiles.length > 0) return scssFiles;
25
+ else if (options.verbose) console.info('\nNo SCSS files found.');
26
+ }
27
+
28
+ function compile(inputPath, options = {}) {
29
+ const defaultOptions = { minify: true, sourceMaps: true, recursive: true, verbose: true, dotFolders: false };
30
+ options = { ...defaultOptions, ...options };
31
+ if (typeof inputPath !== 'string')
32
+ return console.error('ERROR:'
33
+ + ' First argument must be a string representing a file/folder path.');
34
+ const compileOptions = { style: options.minify ? 'compressed' : 'expanded', sourceMap: options.sourceMaps };
35
+ if (fs.existsSync(inputPath)) { // compile based on path arg
36
+ if (inputPath.endsWith('.scss')) { // file path passed
37
+ if (options.verbose) console.info(`Compiling ${ inputPath }...`);
38
+ try { // to compile file passed
39
+ const compileResult = sass.compile(inputPath, compileOptions);
40
+ return { code: compileResult.css, srcMap: compileResult.sourceMap, srcPath: inputPath };
41
+ } catch (err) { console.error(`\nERROR: ${ err.message }\n`); return { error: err }; }
42
+ } else { // dir path passed
43
+ if (options.verbose) console.info('Searching for SCSS files...');
44
+ return findSCSS(inputPath, { recursive: options.recursive, dotFolders: options.dotFolders })
45
+ ?.map(scssPath => { // compile found SCSS files
46
+ if (options.verbose) console.info(`Compiling ${ scssPath }...`);
47
+ try { // to compile found file
48
+ const compileResult = sass.compile(scssPath, compileOptions);
49
+ return { code: compileResult.css, srcMap: compileResult.sourceMap, srcPath: scssPath };
50
+ } catch (err) { console.error(`\nERROR: ${ err.message }\n`); return { error: err }; }
51
+ }).filter(data => !data.error ); // filter out failed compilations
52
+ }
53
+ } else return console.error('First argument must be an existing file or directory.'
54
+ + `\n'${ inputPath }' does not exist.`);
55
+ }
56
+
57
+ // EXPORT functions if script was required
58
+ if (require.main !== module) module.exports = { compile, findSCSS };
59
+
60
+ else { // run as CLI tool
61
+
62
+ // Init UI colors
63
+ const nc = '\x1b[0m', // no color
64
+ br = '\x1b[1;91m', // bright red
65
+ by = '\x1b[1;33m', // bright yellow
66
+ bg = '\x1b[1;92m'; // bright green
67
+
68
+ // Load FLAG settings
69
+ const config = {
70
+ dryRun: process.argv.some(arg => /^--?(?:n|dry-?run)$/.test(arg)),
71
+ includeDotFolders: process.argv.some(arg =>
72
+ /^--?(?:dd?|(?:include-?)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?)$/.test(arg)),
73
+ noSourceMaps: process.argv.some(arg =>
74
+ /^--?(?:S|(?:exclude|disable|no)-?so?u?rce?-?maps?)$/.test(arg)),
75
+ noRecursion: process.argv.some(arg =>
76
+ /^--?(?:R|(?:disable|no)-?recursion)$/.test(arg)),
77
+ noMinify: process.argv.some(arg =>
78
+ /^--?(?:M|(?:disable|no)-?minif(?:y|ication))$/.test(arg)),
79
+ quietMode: process.argv.some(arg => /^--?q(?:uiet)?$/.test(arg))
80
+ };
81
+
82
+ // Show HELP screen if -h or --help passed
83
+ if (process.argv.some(arg => /^--?h(?:elp)?$/.test(arg))) {
84
+ printHelp(`\n${by}scss-to-css [inputPath] [outputPath] [options]${nc}`);
85
+ printHelp('\nPath arguments:');
86
+ printHelp(' [inputPath] '
87
+ + 'Path to SCSS file or directory containing SCSS files to be compiled,'
88
+ + ' relative to the current working directory.');
89
+ printHelp(' [outputPath] '
90
+ + 'Path to file or directory where CSS + sourcemap files will be stored,'
91
+ + ' relative to original file location (if not provided, css/ is used).');
92
+ printHelp('\nConfig options:');
93
+ printHelp(' -n, --dry-run Don\'t actually compile the file(s),'
94
+ + ' just show if they will be processed.');
95
+ printHelp(' -d, --include-dotfolders Include dotfolders in file search.');
96
+ printHelp(' -S, --no-source-maps Prevent source maps from being generated.');
97
+ printHelp(' -M, --no-minify Disable minification of output CSS.');
98
+ printHelp(' -R, --no-recursion Disable recursive file searching.');
99
+ printHelp(' -q, --quiet Suppress all logging except errors.');
100
+ printHelp('\nInfo commands:');
101
+ printHelp(' -h, --help Display this help screen.');
102
+ printHelp(' -v, --version Show version number.');
103
+
104
+ // Show VERSION number if -v or --version passed
105
+ } else if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
106
+ console.info('v' + require('./package.json').version);
107
+
108
+ } else { // run MAIN routine
109
+
110
+ // Init I/O args
111
+ const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
112
+ process.argv.slice(2) // exclude executable and script paths
113
+ .filter(arg => !arg.startsWith('-')) // exclude flags
114
+ .map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
115
+ );
116
+
117
+ // Validate input arg (output arg can be anything)
118
+ const inputPath = path.resolve(process.cwd(), inputArg);
119
+ if (inputArg && !fs.existsSync(inputPath)) {
120
+ console.error(`\n${br}Error: First argument must be an existing file or directory.`
121
+ + `\n'${ inputPath }' does not exist.${nc}`
122
+ + `\n\n${bg}Example valid command: \n>> scss-to-css . output.min.css${nc}`
123
+ + `\n\n${by}For all command options: \n>> scss-to-css --help${nc}`);
124
+ process.exit(1);
125
+ }
126
+
127
+ // Find all eligible JavaScript files or arg-passed file
128
+ printIfNotQuiet('Searching for SCSS files...');
129
+ const scssFiles = inputArg.endsWith('.scss') ? [inputPath]
130
+ : findSCSS(inputPath, { recursive: !config.noRecursion });
131
+
132
+ if (config.dryRun && scssFiles?.length > 0) { // print files to be processed
133
+ console.info(`\n${by}SCSS files to be compiled:${nc}`);
134
+ scssFiles?.forEach(file => console.info(file));
135
+
136
+ } else { // actually compile SCSS files
137
+
138
+ // Build array of compilation data
139
+ const failedPaths = [];
140
+ const compileData = scssFiles?.map(scssPath => {
141
+ const compileResult = compile(scssPath, {
142
+ minify: !config.noMinify, sourceMaps: !config.noSourceMaps, verbose: !config.quietMode });
143
+ if (compileResult.error) failedPaths.push(scssPath);
144
+ return compileResult;
145
+ }).filter(data => !data.error ); // filter out failed compilations
146
+
147
+ // Write array data to files
148
+ compileData?.forEach(({ code, srcMap, srcPath }) => {
149
+ const outputDir = path.join(
150
+ path.dirname(srcPath), // path of file to be minified
151
+ /(?:src|s[ac]ss)$/.test(path.dirname(srcPath)) ? '../css' // + ../css/ if in *(src|sass|scss)/
152
+ : outputArg.endsWith('.css') ? path.dirname(outputArg) // or path from file output arg
153
+ : outputArg || 'css' // or path from folder output arg or css/ if no output arg passed
154
+ );
155
+ const outputFilename = (
156
+ outputArg.endsWith('.css') && inputArg.endsWith('.scss')
157
+ ? path.basename(outputArg).replace(/(\.min)?\.css$/, '')
158
+ : path.basename(srcPath, '.scss')
159
+ ) + '.min.css';
160
+ const outputPath = path.join(outputDir, outputFilename);
161
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
162
+ fs.writeFileSync(outputPath, code, 'utf8');
163
+ if (!config.noSourceMaps) fs.writeFileSync(outputPath + '.map', JSON.stringify(srcMap), 'utf8');
164
+ });
165
+
166
+ // Print final summary
167
+ if (compileData?.length > 0) {
168
+ const cssCntSuffix = compileData.length > 1 ? 's' : '';
169
+ printIfNotQuiet(`\n${bg}Compilation complete!${nc}`);
170
+ printIfNotQuiet(`${ compileData.length } CSS file${ cssCntSuffix }`
171
+ + ( !config.noSourceMaps ? ` + ${ compileData.length } source map${ cssCntSuffix }` : '' )
172
+ + ' generated.');
173
+ } else printIfNotQuiet(`${by}No SCSS files processed successfully.${nc}`);
174
+ if (failedPaths.length > 0) {
175
+ printIfNotQuiet(`\n${br}`
176
+ + `${ failedPaths.length } file${ failedPaths.length > 1 ? 's' : '' }`
177
+ + ` failed to compile:${nc}`);
178
+ failedPaths.forEach(path => printIfNotQuiet(path));
179
+ }
180
+ }
181
+ }
182
+
183
+ // Define LOGGING functions
184
+
185
+ function printHelp(msg) { // wrap msg + indent 2nd+ lines (for --help screen)
186
+ const terminalWidth = process.stdout.columns || 80,
187
+ indentation = 30, lines = [], words = msg.match(/\S+|\s+/g);
188
+
189
+ // Split msg into lines of appropriate lengths
190
+ let currentLine = '';
191
+ words.forEach(word => {
192
+ const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
193
+ if (currentLine.length + word.length > lineLength) { // cap/store it
194
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
195
+ currentLine = '';
196
+ }
197
+ currentLine += word;
198
+ });
199
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
200
+
201
+ // Print formatted msg
202
+ lines.forEach((line, index) => console.info(
203
+ index === 0 ? line // print 1st line unindented
204
+ : ' '.repeat(indentation) + line // print subsequent lines indented
205
+ ));
206
+ }
207
+
208
+ function printIfNotQuiet(msg) { if (!config.quietMode) console.info(msg); }
209
+ }