@adamlui/scss-to-css 1.5.2 → 1.6.0

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,22 @@
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
+ </h6>
11
+ </div>
12
+
1
13
  # { } scss-to-css.js
2
14
 
3
15
  ### Recursively compile all SCSS files into minified CSS.
4
16
 
5
17
  <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
18
  <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>
19
+ <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.0-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
8
20
  <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
21
  <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
22
 
@@ -18,12 +30,19 @@ As a **global utility**:
18
30
  npm install -g @adamlui/scss-to-css
19
31
  ```
20
32
 
21
- As a **dev dependency**, from your project root:
33
+ As a **dev dependency** (e.g. for build scripts):
22
34
 
23
35
  ```
24
36
  npm install -D @adamlui/scss-to-css
25
37
  ```
26
38
 
39
+
40
+ As a **runtime dependency** (e.g. for on-the-fly compilation):
41
+
42
+ ```
43
+ npm install @adamlui/scss-to-css
44
+ ```
45
+
27
46
  ## 💻 Usage
28
47
 
29
48
  The basic **global command** is:
@@ -32,8 +51,6 @@ The basic **global command** is:
32
51
  scss-to-css
33
52
  ```
34
53
 
35
- **💡 Note:** Pass `-n` or `--dry-run` to only see what files will be processed.
36
-
37
54
  Sample output:
38
55
 
39
56
  <img src="https://github.com/adamlui/js-utils/blob/main/scss-to-css/media/images/sample-output.png">
@@ -48,10 +65,10 @@ To specify **input/output** paths:
48
65
  scss-to-css [input_path] [output_path]
49
66
  ```
50
67
 
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).
68
+ - `[input_path]`: Path to SCSS file or directory containing SCSS files to be compiled, relative to the current working directory.
69
+ - `[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
70
 
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`.
71
+ **💡 Note:** If folders are passed, files will be processed recursively unless `-R` or `--no-recursion` is passed.
55
72
 
56
73
  #
57
74
 
@@ -66,6 +83,35 @@ To use as a **package script**, in your project's `package.json`:
66
83
  Replace `<scss-to-css-cmd>` with `scss-to-css` + optional args. Then, `npm run build:css` can be used to run the command.
67
84
  <br><br>
68
85
 
86
+ ### Example commands
87
+
88
+ Compile all SCSS files in the **current directory** (outputs to `css/`):
89
+
90
+ ```
91
+ scss-to-css
92
+ ```
93
+
94
+ Compile all SCSS files in a **specific directory** (outputs to `path/to/your/directory/css/`):
95
+
96
+ ```
97
+ scss-to-css path/to/your/directory
98
+ ```
99
+
100
+ Compile a **specific file** (outputs to `path/to/your/css/file.min.css`):
101
+
102
+ ```
103
+ scss-to-css path/to/your/file.scss
104
+ ```
105
+
106
+ Specify both **input and output** directories (outputs to `output_folder/`):
107
+
108
+ ```
109
+ scss-to-css input_folder output_folder
110
+ ```
111
+
112
+ **💡 Note:** Output CSS is minified unless `-M` or `--no-minify` is passed.
113
+ <br><br>
114
+
69
115
  ### Command line options
70
116
 
71
117
  ```
@@ -83,34 +129,83 @@ Info commands:
83
129
  -v, --version Show version number.
84
130
  ```
85
131
 
86
- ### Example commands
132
+ ## 🔌 API reference
87
133
 
88
- Compile all SCSS files in the **current directory** (outputs to `css/`):
134
+ You can also import **scss-to-css** into your app to use its API methods, both as an ECMAScript module or a CommonJS module.
89
135
 
136
+ #### ESM:
137
+
138
+ ```js
139
+ import * as scssToCSS from '@adamlui/scss-to-css';
90
140
  ```
91
- scss-to-css
141
+
142
+ #### CJS:
143
+
144
+ ```js
145
+ const scssToCSS = require('@adamlui/scss-to-css');
92
146
  ```
93
147
 
94
- Compile all SCSS files in a **specific directory** (outputs to `path/to/your/directory/css/`):
148
+ ### compile(inputPath, options)
149
+
150
+ This function compiles SCSS found in the `inputPath` provided into CSS data.
95
151
 
152
+ If a **file path** is passed, the file's code is compiled to CSS, then an object containing `srcPath` + `code` + `error` is returned:
153
+
154
+ ```js
155
+ const compileResult = scssToCSS.compile('assets/style.scss');
156
+ console.log(compileResult.error); // runtime error, or `undefined` if no error
157
+ console.log(compileResult.code); // compiled CSS output of assets/style.scss
96
158
  ```
97
- scss-to-css path/to/your/directory
159
+
160
+ 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:
161
+
162
+ ```js
163
+ const results = scssToCSS.compile('.');
164
+ results.forEach(result =>
165
+ console.log(result.srcPath) // paths to SCSS files in working directory + all nested directories
166
+ );
167
+ console.log(results[1].code); // compiled CSS output of 2nd SCSS file if found, or `undefined` if not found
98
168
  ```
99
169
 
100
- Compile a **specific file** (outputs to `path/to/your/css/file.min.css`):
170
+ Options are boolean, passed as object properties. For example:
101
171
 
172
+ ```js
173
+ scssToCSS.compile(inputDir, { minify: false });
174
+ // returns data objects where `.code` contains unminified CSS
102
175
  ```
103
- scss-to-css path/to/your/file.scss
176
+
177
+ Possible parameters (and their default settings) are:
178
+
179
+ ```
180
+ recursive (true) Recursively search for nested files if dir path
181
+ passed.
182
+ verbose (true) Show logging in console/terminal.
183
+ dotFolders (false) Include dotfolders in file search.
184
+ minify (true) Minify output CSS.
185
+ sourceMaps (true) Generate CSS source maps.
104
186
  ```
105
187
 
106
- Specify both **input and output** directories (outputs to `output_folder/`):
188
+ ### findSCSS(searchDir, options)
189
+
190
+ 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.
191
+
192
+ Options are boolean, passed as object properties. For example:
107
193
 
194
+ ```js
195
+ scssToCSS.findSCSS(searchDir, { recursive: false });
196
+ // returns array containing filepaths to SCSS files in exactly `searchDir`
108
197
  ```
109
- scss-to-css input_folder output_folder
198
+
199
+ Possible parameters (and their default settings) are:
200
+
201
+ ```
202
+ recursive (true) Recursively search for nested files if dir path
203
+ passed.
204
+ verbose (false) Show logging in console/terminal.
205
+ dotFolders (false) Include dotfolders in file search.
110
206
  ```
111
207
 
112
- **💡 Note:** Output CSS is minified unless `-M` or `--no-minify` is passed.
113
- <br><br>
208
+ <br>
114
209
 
115
210
  ## 💖 Support
116
211
 
@@ -119,7 +214,7 @@ Please consider [giving a GitHub ⭐](https://github.com/adamlui/js-utils) if th
119
214
 
120
215
  ## 🏛️ MIT License
121
216
 
122
- **Copyright (c) 2024 [Adam Lui](https://github.com/adamlui)**
217
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
123
218
 
124
219
  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
220
 
package/docs/LICENSE.md CHANGED
@@ -1,9 +1,21 @@
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
+ </h6>
11
+ </div>
12
+
13
+ # 🏛️ MIT License
14
+
15
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
16
+
17
+ 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:
18
+
19
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
20
+
21
+ 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,17 @@
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
+ </h6>
11
+ </div>
12
+
13
+ # 🛡️ Security Policy
14
+
15
+ If you find a vulnerability, please open a [draft security advisory](https://github.com/adamlui/js-utils/security/advisories/new).
16
+
17
+ 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.
@@ -0,0 +1,21 @@
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;简体中文 |
8
+ <a href="../LICENSE.md">English</a> |
9
+ <a href="../zh-tw/LICENSE.md">繁體中文</a>
10
+ </h6>
11
+ </div>
12
+
13
+ # 🏛️ MIT 许可证
14
+
15
+ **版权所有 © 2023–2024 [刘展鹏 (Adam Lui)](https://github.com/adamlui)**
16
+
17
+ 特此免费向任何获得副本的人授予许可本软件和相关文档文件(『软件』),处理在软件中不受限制,包括但不限于权利使用、复制、修改、合并、发布、分发、再许可和/或出售该软件的副本,并允许该软件是提供这样做,但须满足以下条件:
18
+
19
+ 上述版权声明和本许可声明应包含在所有软件的副本或重要部分。
20
+
21
+ 本软件『按原样』提供,不提供任何形式的明示或保证暗示的,包括但不限于适销性保证,适用于特定目的和非侵权。 在任何情况下都不得作者或版权持有人对任何索赔、损害或其他责任,无论是在合同、侵权或其他方面的行为中,由以下原因引起,出于或与软件或使用或其他交易有关软件。
@@ -0,0 +1,228 @@
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;简体中文 |
8
+ <a href="../..#readme">English</a> |
9
+ <a href="../zh-tw#readme">繁體中文</a>
10
+ </h6>
11
+ </div>
12
+
13
+ # { } scss-to-css.js
14
+
15
+ ### 将所有 SCSS 文件递归编译为缩小的 CSS。
16
+
17
+ <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?label=%E4%B8%8B%E8%BD%BD&logo=npm&logoColor=white&labelColor=464646&style=for-the-badge"></a>
18
+ <a href="#%EF%B8%8F-mit-%E8%AE%B8%E5%8F%AF%E8%AF%81"><img height=31 src="https://img.shields.io/badge/许可证-MIT-red.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
19
+ <a href="https://www.npmjs.com/package/@adamlui/scss-to-css?activeTab=versions"><img height=31 src="https://img.shields.io/badge/最新版本-1.6.0-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
20
+ <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?label=%E6%8B%86%E5%B0%81%E5%B0%BA%E5%AF%B8&style=for-the-badge&logo=ebox&logoColor=white&color=blue&labelColor=464646"></a>
21
+ <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=%E6%BC%8F%E6%B4%9E&color=gold"></a>
22
+
23
+ <img height=8px width="100%" src="https://github.com/adamlui/js-utils/blob/main/docs/images/aqua-separator.png">
24
+
25
+ ## ⚡ 如何安装
26
+
27
+ 作为**全局实用程序**:
28
+
29
+ ```
30
+ npm install -g @adamlui/scss-to-css
31
+ ```
32
+
33
+ 作为**开发人员依赖**(例如,对于构建脚本):
34
+
35
+ ```
36
+ npm install -D @adamlui/scss-to-css
37
+ ```
38
+
39
+
40
+ 作为**运行时依赖**(例如,用于动态编译):
41
+
42
+ ```
43
+ npm install @adamlui/scss-to-css
44
+ ```
45
+
46
+ ## 💻 命令行使用
47
+
48
+ 基本的**全局命令**是:
49
+
50
+ ```
51
+ scss-to-css
52
+ ```
53
+
54
+ 示例输出:
55
+
56
+ <img src="https://github.com/adamlui/js-utils/blob/main/scss-to-css/media/images/sample-output.png">
57
+
58
+ **💡 笔记:** 默认情况下也会生成源映射,除非传递 `-S` 或 `--no-source-maps`。
59
+
60
+ #
61
+
62
+ 指定**输入/输出**路径:
63
+
64
+ ```
65
+ scss-to-css [input_path] [output_path]
66
+ ```
67
+
68
+ - `[input_path]`: SCSS 文件或包含要编译的 SCSS 文件的目录的路径,相对于当前工作目录。
69
+ - `[output_path]`: 将存储 CSS + 源映射文件的文件或目录的路径,相对于原始文件位置(如果未提供,则使用 `css/`)。
70
+
71
+ **💡 注意:** 如果传递文件夹,文件将被递归处理,除非传递 `-R` 或 `--no-recursion`。
72
+
73
+ #
74
+
75
+ 要用作 **包脚本**,请在项目的 `package.json` 中:
76
+
77
+ ```json
78
+ "scripts": {
79
+ "build:css": "<scss-to-css-cmd>"
80
+ },
81
+ ```
82
+
83
+ 将 `<scss-to-css-cmd>` 替换为 `scss-to-css` + 可选参数。 然后,可以使用 `npm run build:css` 来运行该命令。
84
+ <br><br>
85
+
86
+ ### 命令示例
87
+
88
+ 编译 **当前目录** 中的所有 SCSS 文件(输出到 `css/`):
89
+
90
+ ```
91
+ scss-to-css
92
+ ```
93
+
94
+ 编译 **特定目录** 中的所有 SCSS 文件(输出到 `path/to/your/directory/css/`):
95
+
96
+ ```
97
+ scss-to-css path/to/your/directory
98
+ ```
99
+
100
+ 编译一个**特定文件**(输出到 `path/to/your/css/file.min.css`):
101
+
102
+ ```
103
+ scss-to-css path/to/your/file.scss
104
+ ```
105
+
106
+ 指定 **输入和输出** 目录(输出到 `output_folder/`):
107
+
108
+ ```
109
+ scss-to-css input_folder output_folder
110
+ ```
111
+
112
+ **💡 注意:** 除非传递 `-M` 或 `--no-minify` ,否则输出 CSS 会被缩小。
113
+ <br><br>
114
+
115
+ ### 命令行选项
116
+
117
+ ```
118
+ 配置选项:
119
+ -n, --dry-run 实际上并不缩小文件,只是显示它们是否会被处理。
120
+ -d, --include-dotfolders 在文件搜索中包括点文件夹。
121
+ -S, --no-source-maps 防止生成源映射。
122
+ -M, --no-minify 禁用输出 CSS 的缩小。
123
+ -R, --no-recursion 禁用递归文件搜索。
124
+ -q, --quiet 禁止除错误之外的所有日志记录。
125
+
126
+ 信息命令:
127
+ -h, --help 显示帮助屏幕。
128
+ -v, --version 显示版本号。
129
+ ```
130
+
131
+ ## 🔌 API 参考
132
+
133
+ 您还可以将 **scss-to-css** 导入您的应用程序以使用其 API 方法,无论是作为 ECMAScript 模块还是 CommonJS 模块。
134
+
135
+ #### ESM:
136
+
137
+ ```js
138
+ import * as scssToCSS from '@adamlui/scss-to-css';
139
+ ```
140
+
141
+ #### CJS:
142
+
143
+ ```js
144
+ const scssToCSS = require('@adamlui/scss-to-css');
145
+ ```
146
+
147
+ ### compile(inputPath, options)
148
+
149
+ 此函数将在 `inputPath` 中找到的 SCSS 编译为 CSS 数据。
150
+
151
+ 如果传递 **文件路径**,则文件的代码将编译为 CSS,然后返回一个包含 `srcPath` + `code` + `error` 的对象:
152
+
153
+ ```js
154
+ const compileResult = scssToCSS.compile('assets/style.scss');
155
+ console.log(compileResult.error); // 运行时错误,如果没有错误则为 `undefined`
156
+ console.log(compileResult.code); // 编译后的 assets/style.scss CSS 输出
157
+ ```
158
+
159
+ 如果传递 **目录路径**,则搜索 SCSS 文件(默认情况下递归),加载每个文件的代码并编译,然后返回包含 `srcPath` + `code` + `error` 的对象数组:
160
+
161
+ ```js
162
+ const results = scssToCSS.compile('.');
163
+ results.forEach(result =>
164
+ console.log(result.srcPath) // 工作目录 + 所有嵌套目录中 SCSS 文件的路径
165
+ );
166
+ console.log(results[1].code); // 如果找到,则编译第二个 SCSS 文件的 CSS 输出,如果未找到,则为 `undefined`
167
+ ```
168
+
169
+ 选项是布尔值,作为对象属性传递。 例如:
170
+
171
+ ```js
172
+ scssToCSS.compile(inputDir, { minify: false });
173
+ // 返回 `.code` 包含未缩小 CSS 的数据对象
174
+ ```
175
+
176
+ 可能的参数(及其默认设置)有:
177
+
178
+ ```
179
+ recursive (true) 如果传递目录路径,则递归搜索嵌套文件。
180
+ verbose (true) 在控制台/终端中显示日志记录。
181
+ dotFolders (false) 在文件搜索中包括点文件夹。
182
+ minify (true) 缩小输出 CSS。
183
+ sourceMaps (true) 生成 CSS 源映射。
184
+ ```
185
+
186
+ ### findSCSS(searchDir, options)
187
+
188
+ 此函数搜索传递的 `searchDir` 字符串中的所有 SCSS 文件(对于发现 [`compile()`](#compileinputpath-options) 将处理哪些文件很有用)并返回包含其文件路径的数组。
189
+
190
+ 选项是布尔值,作为对象属性传递。 例如:
191
+
192
+ ```js
193
+ scssToCSS.findSCSS(searchDir, { recursive: false });
194
+ // 返回包含恰好位于 `searchDir` 中的 SCSS 文件的文件路径的数组
195
+ ```
196
+
197
+ 可能的参数(及其默认设置)有:
198
+
199
+ ```
200
+ recursive (true) 如果传递目录路径,则递归搜索嵌套文件。
201
+ verbose (false) 在控制台/终端中显示日志记录。
202
+ dotFolders (false) 在文件搜索中包括点文件夹。
203
+ ```
204
+
205
+ <br>
206
+
207
+ ## 💖 支持
208
+
209
+ 如果这对您有帮助,请考虑[给予 GitHub ⭐](https://github.com/adamlui/js-utils)!
210
+ <br><br>
211
+
212
+ ## 🏛️ MIT 许可证
213
+
214
+ **版权所有 © 2023–2024 [刘展鹏 (Adam Lui)](https://github.com/adamlui)**
215
+
216
+ 特此免费向任何获得副本的人授予许可本软件和相关文档文件(『软件』),处理在软件中不受限制,包括但不限于权利使用、复制、修改、合并、发布、分发、再许可和/或出售该软件的副本,并允许该软件是提供这样做,但须满足以下条件:
217
+
218
+ 上述版权声明和本许可声明应包含在所有软件的副本或重要部分。
219
+
220
+ 本软件『按原样』提供,不提供任何形式的明示或保证暗示的,包括但不限于适销性保证,适用于特定目的和非侵权。 在任何情况下都不得作者或版权持有人对任何索赔、损害或其他责任,无论是在合同、侵权或其他方面的行为中,由以下原因引起,出于或与软件或使用或其他交易有关软件。
221
+
222
+ <br>
223
+
224
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
225
+
226
+ <a href="https://github.com/adamlui/js-utils">**家**</a> /
227
+ <a href="https://github.com/adamlui/js-utils/discussions">讨论</a> /
228
+ <a href="#--scss-to-css">回到顶部 ↑</a>
@@ -0,0 +1,17 @@
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;简体中文 |
8
+ <a href="../SECURITY.md">English</a> |
9
+ <a href="../zh-tw/SECURITY.md">繁體中文</a>
10
+ </h6>
11
+ </div>
12
+
13
+ # 🛡️ 安全政策
14
+
15
+ 如果您发现漏洞,请打开[安全公告草案](https://github.com/adamlui/js-utils/security/advisories/new)。
16
+
17
+ 也欢迎拉取请求,但出于安全原因,请发送电子邮件至 <adam@kudoai.com> 并等待回复后再公开。
@@ -0,0 +1,21 @@
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;繁體中文 |
8
+ <a href="../LICENSE.md">English</a> |
9
+ <a href="../zh-cn/LICENSE.md">简体中文</a>
10
+ </h6>
11
+ </div>
12
+
13
+ # 🏛️ MIT 许可证
14
+
15
+ **版權所有 © 2023–2024 [刘展鹏 (Adam Lui)](https://github.com/adamlui)**
16
+
17
+ 特此免費授予任何取得副本的人許可本軟體和相關文件文件(『軟體』),處理在軟體中不受限制,包括但不限於權利使用、複製、修改、合併、發布、分發、再授權和/或出售該軟體的副本,並允許該軟體是提供這樣做,但須滿足以下條件:
18
+
19
+ 上述版權聲明和本許可聲明應包含在所有軟體的副本或重要部分。
20
+
21
+ 本軟體『依現況』提供,不提供任何形式的明示或保證暗示的,包括但不限於適銷性保證,適用於特定目的和非侵權。 在任何情況下都不得作者或版權持有人對任何索賠、損害或其他責任,無論是在合約、侵權或其他方面的行為中,由以下原因引起,出於或與軟體或使用或其他交易有關軟體。
@@ -0,0 +1,227 @@
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;繁體中文 |
8
+ <a href="../..#readme">English</a> |
9
+ <a href="../zh-cn#readme">简体中文</a>
10
+ </h6>
11
+ </div>
12
+
13
+ # { } scss-to-css.js
14
+
15
+ ### 將所有 SCSS 檔案遞歸編譯為縮小的 CSS。
16
+
17
+ <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?label=%E4%B8%8B%E8%BC%89&logo=npm&logoColor=white&labelColor=464646&style=for-the-badge"></a>
18
+ <a href="#%EF%B8%8F-mit-%E8%AE%B8%E5%8F%AF%E8%AF%81"><img height=31 src="https://img.shields.io/badge/許可證-MIT-red.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
19
+ <a href="https://www.npmjs.com/package/@adamlui/scss-to-css?activeTab=versions"><img height=31 src="https://img.shields.io/badge/最新版本-1.6.0-fc7811.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
20
+ <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?label=%E6%8B%86%E5%B0%81%E5%B0%BA%E5%AF%B8&style=for-the-badge&logo=ebox&logoColor=white&color=blue&labelColor=464646"></a>
21
+ <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=%E6%BC%8F%E6%B4%9E&color=gold"></a>
22
+
23
+ <img height=8px width="100%" src="https://github.com/adamlui/js-utils/blob/main/docs/images/aqua-separator.png">
24
+
25
+ ## ⚡ 如何安裝
26
+
27
+ 作為**全域實用程式**:
28
+
29
+ ```
30
+ npm install -g @adamlui/scss-to-css
31
+ ```
32
+
33
+ 作為**開發人員依賴**(例如,對於建置腳本):
34
+
35
+ ```
36
+ npm install -D @adamlui/scss-to-css
37
+ ```
38
+
39
+ 作為**運行時依賴**(例如,用於動態編譯):
40
+
41
+ ```
42
+ npm install @adamlui/scss-to-css
43
+ ```
44
+
45
+ ## 💻 命令列使用
46
+
47
+ 基本的**全域命令**是:
48
+
49
+ ```
50
+ scss-to-css
51
+ ```
52
+
53
+ 範例輸出:
54
+
55
+ <img src="https://github.com/adamlui/js-utils/blob/main/scss-to-css/media/images/sample-output.png">
56
+
57
+ **💡 筆記:** 預設也會產生來源映射,除非傳遞 `-S` 或 `--no-source-maps`。
58
+
59
+ #
60
+
61
+ 指定**輸入/輸出**路徑:
62
+
63
+ ```
64
+ scss-to-css [input_path] [output_path]
65
+ ```
66
+
67
+ - `[input_path]`: SCSS 檔案或包含要編譯的 SCSS 檔案的目錄的路徑,相對於目前工作目錄。
68
+ - `[output_path]`: 將儲存 CSS + 來源對應檔案的檔案或目錄的路徑,相對於原始檔案位置(如果未提供,則使用 `css/`)。
69
+
70
+ **💡 注意:** 如果傳遞資料夾,檔案將被遞歸處理,除非傳遞 `-R` 或 `--no-recursion`。
71
+
72
+ #
73
+
74
+ 若要用作 **套件腳本**,請在專案的 `package.json` 中:
75
+
76
+ ```json
77
+ "scripts": {
78
+ "build:css": "<scss-to-css-cmd>"
79
+ },
80
+ ```
81
+
82
+ 將 `<scss-to-css-cmd>` 替換為 `scss-to-css` + 可選參數。 然後,可以使用 `npm run build:css` 來執行該指令。
83
+ <br><br>
84
+
85
+ ### 命令範例
86
+
87
+ 編譯 **目前目錄** 中的所有 SCSS 檔案(輸出到 `css/`):
88
+
89
+ ```
90
+ scss-to-css
91
+ ```
92
+
93
+ 編譯 **特定目錄** 中的所有 SCSS 檔案(輸出到 `path/to/your/directory/css/`):
94
+
95
+ ```
96
+ scss-to-css path/to/your/directory
97
+ ```
98
+
99
+ 編譯一個**特定檔案**(輸出到 `path/to/your/css/file.min.css`):
100
+
101
+ ```
102
+ scss-to-css path/to/your/file.scss
103
+ ```
104
+
105
+ 指定 **輸入和輸出** 目錄(輸出到 `output_folder/`):
106
+
107
+ ```
108
+ scss-to-css input_folder output_folder
109
+ ```
110
+
111
+ **💡 注意:** 除非傳遞 `-M` 或 `--no-minify` ,否則輸出 CSS 會被縮小。
112
+ <br><br>
113
+
114
+ ### 命令列選項
115
+
116
+ ```
117
+ 配置選項:
118
+ -n, --dry-run 實際上並不會縮小文件,只是顯示它們是否會被處理。
119
+ -d, --include-dotfolders 在檔案搜尋中包含點資料夾。
120
+ -S, --no-source-maps 防止產生來源映射。
121
+ -M, --no-minify 禁用輸出 CSS 的縮小。
122
+ -R, --no-recursion 停用遞歸檔案搜尋。
123
+ -q, --quiet 禁止錯誤以外的所有日誌記錄。
124
+
125
+ 訊息命令:
126
+ -h, --help 顯示幫助畫面。
127
+ -v, --version 顯示版本號。
128
+ ```
129
+
130
+ ## 🔌 API 參考
131
+
132
+ 您也可以將 **scss-to-css** 匯入您的應用程式以使用其 API 方法,無論是作為 ECMAScript 模組還是 CommonJS 模組。
133
+
134
+ #### ESM:
135
+
136
+ ```js
137
+ import * as scssToCSS from '@adamlui/scss-to-css';
138
+ ```
139
+
140
+ #### CJS:
141
+
142
+ ```js
143
+ const scssToCSS = require('@adamlui/scss-to-css');
144
+ ```
145
+
146
+ ### compile(inputPath, options)
147
+
148
+ 此函數將在 `inputPath` 中找到的 SCSS 編譯為 CSS 資料。
149
+
150
+ 如果傳遞 **檔案路徑**,則檔案的程式碼將編譯為 CSS,然後傳回一個包含 `srcPath` + `code` + `error` 的物件:
151
+
152
+ ```js
153
+ const compileResult = scssToCSS.compile('assets/style.scss');
154
+ console.log(compileResult.error); // 執行階段錯誤,如果沒有錯誤則為 `undefined`
155
+ console.log(compileResult.code); // 編譯後的 assets/style.scss CSS 輸出
156
+ ```
157
+
158
+ 如果传递 **目录路径**,则搜索 SCSS 文件(默认情况下递归),加载每个文件的代码并编译,然后返回包含 `srcPath` + `code` + `error` 的对象数组:
159
+
160
+ ```js
161
+ const results = scssToCSS.compile('.');
162
+ results.forEach(result =>
163
+ console.log(result.srcPath) // 工作目錄 + 所有巢狀目錄中 SCSS 檔案的路徑
164
+ );
165
+ console.log(results[1].code); // 如果找到,則編譯第二個 SCSS 檔案的 CSS 輸出,如果找不到,則為 `undefined`
166
+ ```
167
+
168
+ 選項是布林值,作為物件屬性傳遞。 例如:
169
+
170
+ ```js
171
+ scssToCSS.compile(inputDir, { minify: false });
172
+ // 傳回 `.code` 包含未縮小 CSS 的資料對象
173
+ ```
174
+
175
+ 可能的參數(及其預設設定)有:
176
+
177
+ ```
178
+ recursive (true) 如果傳遞目錄路徑,則遞歸搜尋巢狀檔案。
179
+ verbose (true) 在控制台/終端機中顯示日誌記錄。
180
+ dotFolders (false) 在檔案搜尋中包含點資料夾。
181
+ minify (true) 縮小輸出 CSS。
182
+ sourceMaps (true) 產生 CSS 來源映射。
183
+ ```
184
+
185
+ ### findSCSS(searchDir, options)
186
+
187
+ 此函數搜尋傳遞的 `searchDir` 字串中的所有 SCSS 檔案(對於發現 [`compile()`](#compileinputpath-options) 將處理哪些檔案很有用)並傳回包含其檔案路徑的陣列。
188
+
189
+ 選項是布林值,作為物件屬性傳遞。 例如:
190
+
191
+ ```js
192
+ scssToCSS.findSCSS(searchDir, { recursive: false });
193
+ // 傳回包含恰好位於 `searchDir` 中的 SCSS 檔案的檔案路徑的陣列
194
+ ```
195
+
196
+ 可能的參數(及其預設設定)有:
197
+
198
+ ```
199
+ recursive (true) 如果傳遞目錄路徑,則遞歸搜尋巢狀檔案。
200
+ verbose (false) 在控制台/終端機中顯示日誌記錄。
201
+ dotFolders (false) 在檔案搜尋中包含點資料夾。
202
+ ```
203
+
204
+ <br>
205
+
206
+ ## 💖 支援
207
+
208
+ 如果這對您有幫助,請考慮[給予 GitHub ⭐](https://github.com/adamlui/js-utils)!
209
+ <br><br>
210
+
211
+ ## 🏛️ MIT 许可证
212
+
213
+ **版權所有 © 2023–2024 [刘展鹏 (Adam Lui)](https://github.com/adamlui)**
214
+
215
+ 特此免費授予任何取得副本的人許可本軟體和相關文件文件(『軟體』),處理在軟體中不受限制,包括但不限於權利使用、複製、修改、合併、發布、分發、再授權和/或出售該軟體的副本,並允許該軟體是提供這樣做,但須滿足以下條件:
216
+
217
+ 上述版權聲明和本許可聲明應包含在所有軟體的副本或重要部分。
218
+
219
+ 本軟體『依現況』提供,不提供任何形式的明示或保證暗示的,包括但不限於適銷性保證,適用於特定目的和非侵權。 在任何情況下都不得作者或版權持有人對任何索賠、損害或其他責任,無論是在合約、侵權或其他方面的行為中,由以下原因引起,出於或與軟體或使用或其他交易有關軟體。
220
+
221
+ <br>
222
+
223
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
224
+
225
+ <a href="https://github.com/adamlui/js-utils">**家**</a> /
226
+ <a href="https://github.com/adamlui/js-utils/discussions">讨论</a> /
227
+ <a href="#--scss-to-css">回到顶部 ↑</a>
@@ -0,0 +1,17 @@
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;繁體中文 |
8
+ <a href="../SECURITY.md">English</a> |
9
+ <a href="../zh-cn/SECURITY.md">简体中文</a>
10
+ </h6>
11
+ </div>
12
+
13
+ # 🛡️ 安全策略
14
+
15
+ 如果您發現漏洞,請打開[安全公告草案](https://github.com/adamlui/js-utils/security/advisories/new)。
16
+
17
+ 也歡迎拉取請求,但出於安全原因,請發送電子郵件至 <adam@kudoai.com> 並等待回復後再公開。
package/package.json CHANGED
@@ -1,48 +1,48 @@
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.0",
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
+ }
package/scss-to-css.js CHANGED
@@ -1,162 +1,208 @@
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 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
+ return findSCSS(inputPath, { recursive: options.recursive, dotFolders: options.dotFolders })
44
+ ?.map(scssPath => { // compile found SCSS files
45
+ if (options.verbose) console.info(`Compiling ${ scssPath }...`);
46
+ try { // to compile found file
47
+ const compileResult = sass.compile(scssPath, compileOptions);
48
+ return { code: compileResult.css, srcMap: compileResult.sourceMap, srcPath: scssPath };
49
+ } catch (err) { console.error(`\nERROR: ${ err.message }\n`); return { error: err }; }
50
+ }).filter(data => !data.error ); // filter out failed compilations
51
+ }
52
+ } else return console.error('First argument must be an existing file or directory.'
53
+ + `\n'${ inputPath }' does not exist.`);
54
+ }
55
+
56
+ // EXPORT functions if script was required
57
+ if (require.main !== module) module.exports = { compile, findSCSS };
58
+
59
+ else { // run as CLI tool
60
+
61
+ // Init UI colors
62
+ const nc = '\x1b[0m', // no color
63
+ br = '\x1b[1;91m', // bright red
64
+ by = '\x1b[1;33m', // bright yellow
65
+ bg = '\x1b[1;92m'; // bright green
66
+
67
+ // Load FLAG settings
68
+ const config = {
69
+ dryRun: process.argv.some(arg => /^--?(?:n|dry-?run)$/.test(arg)),
70
+ includeDotFolders: process.argv.some(arg =>
71
+ /^--?(?:dd?|(?:include-?)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?)$/.test(arg)),
72
+ noSourceMaps: process.argv.some(arg =>
73
+ /^--?(?:S|(?:exclude|disable|no)-?so?u?rce?-?maps?)$/.test(arg)),
74
+ noRecursion: process.argv.some(arg =>
75
+ /^--?(?:R|(?:disable|no)-?recursion)$/.test(arg)),
76
+ noMinify: process.argv.some(arg =>
77
+ /^--?(?:M|(?:disable|no)-?minif(?:y|ication))$/.test(arg)),
78
+ quietMode: process.argv.some(arg => /^--?q(?:uiet)?$/.test(arg))
79
+ };
80
+
81
+ // Show HELP screen if -h or --help passed
82
+ if (process.argv.some(arg => /^--?h(?:elp)?$/.test(arg))) {
83
+ printHelp(`\n${by}scss-to-css [inputPath] [outputPath] [options]${nc}`);
84
+ printHelp('\nPath arguments:');
85
+ printHelp(' [inputPath] '
86
+ + 'Path to SCSS file or directory containing SCSS files to be compiled,'
87
+ + ' relative to the current working directory.');
88
+ printHelp(' [outputPath] '
89
+ + 'Path to file or directory where CSS + sourcemap files will be stored,'
90
+ + ' relative to original file location (if not provided, css/ is used).');
91
+ printHelp('\nConfig options:');
92
+ printHelp(' -n, --dry-run Don\'t actually compile the file(s),'
93
+ + ' just show if they will be processed.');
94
+ printHelp(' -d, --include-dotfolders Include dotfolders in file search.');
95
+ printHelp(' -S, --no-source-maps Prevent source maps from being generated.');
96
+ printHelp(' -M, --no-minify Disable minification of output CSS.');
97
+ printHelp(' -R, --no-recursion Disable recursive file searching.');
98
+ printHelp(' -q, --quiet Suppress all logging except errors.');
99
+ printHelp('\nInfo commands:');
100
+ printHelp(' -h, --help Display this help screen.');
101
+ printHelp(' -v, --version Show version number.');
102
+
103
+ // Show VERSION number if -v or --version passed
104
+ } else if (process.argv.some(arg => /^--?ve?r?s?i?o?n?$/.test(arg))) {
105
+ console.info('v' + require('./package.json').version);
106
+
107
+ } else { // run MAIN routine
108
+
109
+ // Init I/O args
110
+ const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
111
+ process.argv.slice(2) // exclude executable and script paths
112
+ .filter(arg => !arg.startsWith('-')) // exclude flags
113
+ .map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
114
+ );
115
+
116
+ // Validate input arg (output arg can be anything)
117
+ const inputPath = path.resolve(process.cwd(), inputArg);
118
+ if (inputArg && !fs.existsSync(inputPath)) {
119
+ console.error(`\n${br}Error: First argument must be an existing file or directory.`
120
+ + `\n'${ inputPath }' does not exist.${nc}`
121
+ + `\n\n${bg}Example valid command: \n>> scss-to-css . output.min.css${nc}`
122
+ + `\n\n${by}For all command options: \n>> scss-to-css --help${nc}`);
123
+ process.exit(1);
124
+ }
125
+
126
+ // Find all eligible JavaScript files or arg-passed file
127
+ const scssFiles = inputArg.endsWith('.scss') ? [inputPath]
128
+ : findSCSS(inputPath, { recursive: !config.noRecursion });
129
+
130
+ if (config.dryRun && scssFiles?.length > 0) { // print files to be processed
131
+ console.info(`\n${by}SCSS files to be compiled:${nc}`);
132
+ scssFiles?.forEach(file => console.info(file));
133
+
134
+ } else { // actually compile SCSS files
135
+ printIfNotQuiet(''); // line break before first log
136
+
137
+ // Build array of compilation data
138
+ const failedPaths = [];
139
+ const compileData = scssFiles?.map(scssPath => {
140
+ const compileResult = compile(scssPath, {
141
+ minify: !config.noMinify, sourceMaps: !config.noSourceMaps, verbose: !config.quietMode });
142
+ if (compileResult.error) failedPaths.push(scssPath);
143
+ return compileResult;
144
+ }).filter(data => !data.error ); // filter out failed compilations
145
+
146
+ // Write array data to files
147
+ compileData?.forEach(({ code, srcMap, srcPath }) => {
148
+ const outputDir = path.join(
149
+ path.dirname(srcPath), // path of file to be minified
150
+ /(?:src|s[ac]ss)$/.test(path.dirname(srcPath)) ? '../css' // + ../css/ if in *(src|sass|scss)/
151
+ : outputArg.endsWith('.css') ? path.dirname(outputArg) // or path from file output arg
152
+ : outputArg || 'css' // or path from folder output arg or css/ if no output arg passed
153
+ );
154
+ const outputFilename = (
155
+ outputArg.endsWith('.css') && inputArg.endsWith('.scss')
156
+ ? path.basename(outputArg).replace(/(\.min)?\.css$/, '')
157
+ : path.basename(srcPath, '.scss')
158
+ ) + '.min.css';
159
+ const outputPath = path.join(outputDir, outputFilename);
160
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
161
+ fs.writeFileSync(outputPath, code, 'utf8');
162
+ if (!config.noSourceMaps) fs.writeFileSync(outputPath + '.map', JSON.stringify(srcMap), 'utf8');
163
+ });
164
+
165
+ // Print final summary
166
+ if (compileData?.length > 0) {
167
+ const cssCntSuffix = compileData.length > 1 ? 's' : '';
168
+ printIfNotQuiet(`\n${bg}Compilation complete!${nc}`);
169
+ printIfNotQuiet(`${ compileData.length } CSS file${ cssCntSuffix }`
170
+ + ( !config.noSourceMaps ? ` + ${ compileData.length } source map${ cssCntSuffix }` : '' )
171
+ + ' generated.');
172
+ } else printIfNotQuiet(`${by}No SCSS files processed successfully.${nc}`);
173
+ if (failedPaths.length > 0) {
174
+ printIfNotQuiet(`\n${br}`
175
+ + `${ failedPaths.length } file${ failedPaths.length > 1 ? 's' : '' }`
176
+ + ` failed to compile:${nc}`);
177
+ failedPaths.forEach(path => printIfNotQuiet(path));
178
+ }
179
+ }
180
+ }
181
+
182
+ // Define LOGGING functions
183
+
184
+ function printHelp(msg) { // wrap msg + indent 2nd+ lines (for --help screen)
185
+ const terminalWidth = process.stdout.columns || 80,
186
+ indentation = 30, lines = [], words = msg.match(/\S+|\s+/g);
187
+
188
+ // Split msg into lines of appropriate lengths
189
+ let currentLine = '';
190
+ words.forEach(word => {
191
+ const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
192
+ if (currentLine.length + word.length > lineLength) { // cap/store it
193
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
194
+ currentLine = '';
195
+ }
196
+ currentLine += word;
197
+ });
198
+ lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
199
+
200
+ // Print formatted msg
201
+ lines.forEach((line, index) => console.info(
202
+ index === 0 ? line // print 1st line unindented
203
+ : ' '.repeat(indentation) + line // print subsequent lines indented
204
+ ));
205
+ }
206
+
207
+ function printIfNotQuiet(msg) { if (!config.quietMode) console.info(msg); }
208
+ }