@adamlui/scss-to-css 1.7.2 → 1.7.4

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,22 +1,26 @@
1
- <div align="center">
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
- <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/de#readme">Deutsch</a> |
15
- <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/es#readme">Español</a> |
16
- <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/fr#readme">Français</a> |
17
- <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/pt#readme">Português</a>
18
- </h6>
19
- </div>
1
+ <table align="center">
2
+ <td align="center" width=1000>
3
+ <h6>
4
+ <picture>
5
+ <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">
6
+ <img height=14 src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/earth-icon/black/icon32.svg">
7
+ </picture>
8
+ &nbsp;English |
9
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/zh-cn#readme">简体中文</a> |
10
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/zh-tw#readme">繁體中文</a> |
11
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/hi#readme">हिंदी</a> |
12
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/bn#readme">বাংলা</a> |
13
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/mr#readme">मराठी</a> |
14
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/pa#readme">ਪੰਜਾਬੀ</a> |
15
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/de#readme">Deutsch</a> |
16
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/es#readme">Español</a> |
17
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/fr#readme">Français</a> |
18
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/it#readme">Italiano</a> |
19
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/nl#readme">Nederlands</a> |
20
+ <a href="https://github.com/adamlui/js-utils/tree/main/scss-to-css/docs/pt#readme">Português</a>
21
+ </h6>
22
+ </td>
23
+ </table>
20
24
 
21
25
  # { } scss-to-css
22
26
 
@@ -24,7 +28,7 @@
24
28
 
25
29
  <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&color=af68ff&logoColor=white&labelColor=464646&style=for-the-badge"></a>
26
30
  <a href="#%EF%B8%8F-mit-license"><img height=31 src="https://img.shields.io/badge/License-MIT-orange.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
27
- <a href="https://github.com/adamlui/js-utils/releases/tag/scss-to-css-1.7.2"><img height=31 src="https://img.shields.io/badge/Latest_Build-1.7.2-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
31
+ <a href="https://github.com/adamlui/js-utils/releases/tag/scss-to-css-1.7.4"><img height=31 src="https://img.shields.io/badge/Latest_Build-1.7.4-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
28
32
  <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>
29
33
  <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>
30
34
 
@@ -219,8 +223,10 @@ const searchResults = scssToCSS.findSCSS('assets/scss', { recursive: false });
219
223
  console.log(searchResults);
220
224
 
221
225
  /* sample output:
222
- Searching for SCSS files...
223
- Search complete. 2 files found.
226
+
227
+ findSCSS() » Searching for SCSS files...
228
+ findSCSS() » Search complete! 2 files found.
229
+ findSCSS() » Check returned array.
224
230
  [
225
231
  'E:\\js\\utils\\minify.js\\assets\\scss\\foo.scss',
226
232
  'E:\\js\\utils\\minify.js\\assets\\scss\\bar.scss'
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ const c=require("fs"),l=require("path"),t=require("sass");function a(s,r={}){var e={recursive:!0,verbose:!0,dotFolders:!1};if(r={...e,...r},"string"!=typeof s)return console.error("findSCSS() » ERROR: 1st arg <searchDir> must be a string.");var o=l.resolve(process.cwd(),s);if(!c.existsSync(o))return console.error("findSCSS() » ERROR: 1st arg <searchDir> must be an existing directory.\n"+`findSCSS() » ${o} does not exist.`);for(const t of Object.keys(r))if(!Object.prototype.hasOwnProperty.call(e,t)){if("isRecursing"!==t)return console.error(`findSCSS() » ERROR: \`${t}\` is an invalid option.
3
+ `+`findSCSS() » Valid options: [ ${Object.keys(e).join(", ")} ]`);if("boolean"!=typeof r[t])return console.error(`findSCSS() » ERROR: \`${t}\` option can only be set to \`true\` or \`false\`.`)}const i=c.readdirSync(s),n=[];return r.verbose&&!r.isRecursing&&console.info("\nfindSCSS() » Searching for SCSS files..."),i.forEach(e=>{var o=l.resolve(s,e);c.statSync(o).isDirectory()&&"node_modules"!=e&&(r.dotFolders||!e.startsWith("."))&&r.recursive?n.push(...a(o,{...r,isRecursing:!0})):e.endsWith(".scss")&&n.push(o)}),!r.isRecursing&&r.verbose&&console.info("findSCSS() » Search complete! "+(0===n.length?"No":n.length)+` file${1<n.length?"s":""} found.`+("compile"!==a.caller.name&&require.main!==module?"\nfindSCSS() » Check returned array.":"")),r.isRecursing||0<n.length?n:[]}function s(e,s={}){var o={minify:!0,sourceMaps:!0,recursive:!0,verbose:!0,dotFolders:!1};if(s={...o,...s},"string"!=typeof e)return console.error("findSCSS() » ERROR: 1st arg <inputPath> must be a string.");if(e=l.resolve(process.cwd(),e),!c.existsSync(e))return console.error("findSCSS() » ERROR: 1st arg <inputPath> must be an existing directory or file.\n"+`findSCSS() » ${e} does not exist.`);for(const n of Object.keys(s)){if(!Object.prototype.hasOwnProperty.call(o,n))return console.error(`compile() » ERROR: \`${n}\` is an invalid option.
4
+ `+`compile() » Valid options: [ ${Object.keys(o).join(", ")} ]`);if("boolean"!=typeof s[n])return console.error(`compile() » ERROR: \`${n}\` option can only be set to \`true\` or \`false\`.`)}const r={style:s.minify?"compressed":"expanded",sourceMap:s.sourceMaps};if(c.existsSync(e)){if(!e.endsWith(".scss"))return a(e,{recursive:s.recursive,verbose:s.verbose,dotFolders:s.dotFolders})?.map(e=>{s.verbose&&console.info(`compile() » Compiling ${e}...`);try{var o=t.compile(e,r);return{code:o.css,srcMap:o.sourceMap,srcPath:e}}catch(e){return console.error(`
5
+ compile() » ERROR: ${e.message}
6
+ `),{error:e}}}).filter(e=>!e.error);s.verbose&&console.info(`compile() » Compiling ${e}...`);try{var i=t.compile(e,r);return{code:i.css,srcMap:i.sourceMap,srcPath:l.resolve(process.cwd(),e)}}catch(e){return console.error(`
7
+ compile() » ERROR: ${e.message}
8
+ `),{error:e}}}}if(require.main!==module)module.exports={compile:s,findSCSS:a};else{const i="",n="",d="",e="",f={},u={dryRun:/^--?(?:n|dry-?run)$/,includeDotFolders:/^--?(?:dd?|(?:include-?)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?=?(?:true|1)?)$/,noSourceMaps:/^--?(?:S|(?:exclude|disable|no)-?so?u?rce?-?maps?|so?u?rce?-?maps?=(?:false|0))$/,noRecursion:/^--?(?:R|(?:disable|no)-?recursi(?:on|ve)|recursi(?:on|ve)=(?:false|0))$/,noMinify:/^--?(?:M|(?:disable|no)-?minif(?:y|ication)|minif(?:y|ication)=(?:false|0))$/,quietMode:/^--?q(?:uiet)?(?:-?mode)?$/,help:/^--?h(?:elp)?$/,version:/^--?ve?r?s?i?o?n?$/};if(process.argv.forEach(o=>{var e;o.startsWith("-")&&((e=Object.keys(u).find(e=>u[e].test(o)))?f[e]=!0:(console.error(`
9
+ ${n}ERROR: Arg [${o}] not recognized.`+i),console.info(`
10
+ ${d}Valid arguments are below.`+i),r(["configOptions","infoCmds"]),process.exit(1)))}),process.argv.some(e=>u.help.test(e)))r();else if(process.argv.some(e=>u.version.test(e)))console.info("v"+require("./package.json").version);else{const[p="",m=""]=process.argv.slice(2).filter(e=>!e.startsWith("-")).map(e=>e.replace(/^\/*/,"")),S=l.resolve(process.cwd(),p),h=(p&&!c.existsSync(S)&&(console.error(`
11
+ ${n}Error: First argument can only be an existing file or directory.`+`
12
+ '${S}' does not exist.`+i+`
13
+
14
+ ${e}Example valid command:
15
+ >> scss-to-css . output.min.css`+i+`
16
+
17
+ ${d}For all command options:
18
+ >> scss-to-css --help`+i),process.exit(1)),p.endsWith(".scss")?[S]:a(S,{recursive:!f.noRecursion,verbose:!f.quietMode}));if(f.dryRun)0<h.length?(console.info(`
19
+ ${d}SCSS files to be compiled:`+i),h.forEach(e=>console.info(e))):console.info(d+`
20
+ No SCSS files will be compiled.`+i);else{const g=[],v=h.map(e=>{var o=s(e,{minify:!f.noMinify,sourceMaps:!f.noSourceMaps,verbose:!f.quietMode});return o.error&&g.push(e),o}).filter(e=>!e.error);if(v?.forEach(({code:e,srcMap:o,srcPath:s})=>{var r=l.join(l.dirname(s),/(?:src|s[ac]ss)$/.test(l.dirname(s))?"../css":m.endsWith(".css")?l.dirname(m):m||"css"),s=(m.endsWith(".css")&&p.endsWith(".scss")?l.basename(m).replace(/(\.min)?\.css$/,""):l.basename(s,".scss"))+".min.css",s=l.join(r,s);c.existsSync(r)||c.mkdirSync(r,{recursive:!0}),c.writeFileSync(s,e,"utf8"),f.noSourceMaps||c.writeFileSync(s+".map",JSON.stringify(o),"utf8")}),0<v?.length){const y=1<v.length?"s":"";o(`
21
+ ${e}Compilation complete!`+i),o(v.length+" CSS file"+y+(f.noSourceMaps?"":` + ${v.length} source map`+y)+" generated.")}else o(d+"No SCSS files processed."+i);0<g.length&&(o(`
22
+ `+n+g.length+" file"+(1<g.length?"s":"")+" failed to compile:"+i),g.forEach(e=>o(e)))}}function r(e=["cmdFormat","pathArgs","configOptions","infoCmds"]){const o={cmdFormat:[`
23
+ ${d}scss-to-css [inputPath] [outputPath] [options]`+i],pathArgs:["\nPath arguments:"," [inputPath] Path to SCSS file or directory containing SCSS files to be compiled, relative to the current working directory."," [outputPath] Path to file or directory where CSS + sourcemap files will be stored, relative to original file location (if not provided, css/ is used)."],configOptions:["\nConfig options:"," -n, --dry-run Don't actually compile the file(s), just show if they will be processed."," -d, --include-dotfolders Include dotfolders in file search."," -S, --no-source-maps Prevent source maps from being generated."," -M, --no-minify Disable minification of output CSS."," -R, --no-recursion Disable recursive file searching."," -q, --quiet Suppress all logging except errors."],infoCmds:["\nInfo commands:"," -h, --help Display help screen."," -v, --version Show version number."]};e.forEach(e=>{o[e]?.forEach(e=>{{const r=process.stdout.columns||80,i=[],o=e.match(/\S+|\s+/g);let s="";o.forEach(e=>{var o=r-(0===i.length?0:30);s.length+e.length>o&&(i.push(0===i.length?s:s.trimStart()),s=""),s+=e}),i.push(0===i.length?s:s.trimStart()),i.forEach((e,o)=>console.info(0===o?e:" ".repeat(30)+e))}})})}function o(e){f.quietMode||console.info(e)}}
package/docs/LICENSE.md CHANGED
@@ -1,4 +1,4 @@
1
- <div align="right">
1
+ <div align="center">
2
2
  <h6>
3
3
  <picture>
4
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">
@@ -14,6 +14,8 @@
14
14
  <a href="de/LICENSE.md">Deutsch</a> |
15
15
  <a href="es/LICENSE.md">Español</a> |
16
16
  <a href="fr/LICENSE.md">Français</a> |
17
+ <a href="it/LICENSE.md">Italiano</a> |
18
+ <a href="nl/LICENSE.md">Nederlands</a> |
17
19
  <a href="pt/LICENSE.md">Português</a>
18
20
  </h6>
19
21
  </div>
package/docs/SECURITY.md CHANGED
@@ -1,4 +1,4 @@
1
- <div align="right">
1
+ <div align="center">
2
2
  <h6>
3
3
  <picture>
4
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">
@@ -14,6 +14,8 @@
14
14
  <a href="de/SECURITY.md">Deutsch</a> |
15
15
  <a href="es/SECURITY.md">Español</a> |
16
16
  <a href="fr/SECURITY.md">Français</a> |
17
+ <a href="it/SECURITY.md">Italiano</a> |
18
+ <a href="nl/SECURITY.md">Nederlands</a> |
17
19
  <a href="pt/SECURITY.md">Português</a>
18
20
  </h6>
19
21
  </div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamlui/scss-to-css",
3
- "version": "1.7.2",
3
+ "version": "1.7.4",
4
4
  "description": "Recursively compile all SCSS files into minified CSS",
5
5
  "author": {
6
6
  "name": "Adam Lui",
@@ -9,13 +9,19 @@
9
9
  },
10
10
  "homepage": "https://github.com/adamlui/js-utils",
11
11
  "license": "MIT",
12
- "main": "scss-to-css.js",
12
+ "main": "dist/scss-to-css.min.js",
13
+ "files": [
14
+ "dist",
15
+ "docs/",
16
+ "!docs/*/"
17
+ ],
13
18
  "bin": {
14
- "scsstocss": "scss-to-css.js",
15
- "scss-to-css": "scss-to-css.js"
19
+ "scsstocss": "dist/scss-to-css.min.js",
20
+ "scss-to-css": "dist/scss-to-css.min.js"
16
21
  },
17
22
  "scripts": {
18
23
  "test": "echo \"Error: no test specified\" && exit 1",
24
+ "build": "minify-js scss-to-css.js dist",
19
25
  "bump:patch": "bash utils/bump.sh patch",
20
26
  "bump:minor": "bash utils/bump.sh minor",
21
27
  "bump:major": "bash utils/bump.sh major",
@@ -46,5 +52,8 @@
46
52
  "funding": {
47
53
  "type": "github",
48
54
  "url": "https://github.com/sponsors/adamlui"
55
+ },
56
+ "devDependencies": {
57
+ "@adamlui/minify.js": "^1.4.6"
49
58
  }
50
59
  }
package/scss-to-css.js DELETED
@@ -1,286 +0,0 @@
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
-
12
- // Init options
13
- const defaultOptions = { recursive: true, verbose: true, dotFolders: false };
14
- options = { ...defaultOptions, ...options };
15
-
16
- // Validate searchDir
17
- if (!searchDir) return console.error(
18
- 'findSCSS() error: Please supply a `searchDir` arg.');
19
- else if (typeof searchDir !== 'string') return console.error(
20
- 'findSCSS() error: Arg `searchDir` must be a string.');
21
- else { // verify searchDir path existence
22
- const searchPath = path.resolve(process.cwd(), searchDir);
23
- if (!fs.existsSync(searchPath)) return console.error(
24
- 'findSCSS() error: Arg `searchDir` must be an existing directory.'
25
- + `\n'${ searchPath }' does not exist.`);
26
- }
27
-
28
- // Validate options
29
- for (const key of Object.keys(options)) {
30
- if (!Object.prototype.hasOwnProperty.call(defaultOptions, key))
31
- if (key !== 'isRecursing') return console.error(
32
- `findSCSS() error: \`${ key }\` is an invalid option.`
33
- + `\nValid options: [ ${Object.keys(defaultOptions).join(', ')} ]`);
34
- else if (typeof options[key] !== 'boolean') return console.error(
35
- `findSCSS() error: \`${ key }\` option must be set to \`true\` or \`false\`.`);
36
- }
37
-
38
- // Search for SCSS
39
- const dirFiles = fs.readdirSync(searchDir), scssFiles = [];
40
- if (options.verbose && !options.isRecursing) console.info('\nSearching for SCSS files...');
41
- dirFiles.forEach(file => {
42
- const filePath = path.resolve(searchDir, file);
43
- if (fs.statSync(filePath).isDirectory() && file != 'node_modules'
44
- && (options.dotFolders || !file.startsWith('.')) && options.recursive)
45
- scssFiles.push( // recursively find SCSS in eligible dir
46
- ...findSCSS(filePath, { ...options, isRecursing: true }));
47
- else if (file.endsWith('.scss')) // SCSS file found
48
- scssFiles.push(filePath); // store it for compilation
49
- });
50
-
51
- // Log/return final result
52
- if (!options.isRecursing && options.verbose) {
53
- console.info('Search complete. '
54
- + ( scssFiles.length === 0 ? 'No' : scssFiles.length )
55
- + ` file${ scssFiles.length > 1 ? 's' : '' } found.`);
56
- }
57
- return options.isRecursing || scssFiles.length > 0 ? scssFiles : [];
58
- }
59
-
60
- function compile(inputPath, options = {}) {
61
-
62
- // Init options
63
- const defaultOptions = { minify: true, sourceMaps: true, recursive: true, verbose: true, dotFolders: false };
64
- options = { ...defaultOptions, ...options };
65
-
66
- // Validate inputPath
67
- if (typeof inputPath !== 'string') return console.error(
68
- 'compile() error: Arg `inputPath` must be a string.');
69
- else { // verify inputPath path existence
70
- inputPath = path.resolve(process.cwd(), inputPath);
71
- if (!fs.existsSync(inputPath)) return console.error(
72
- 'compile() error: Arg `inputPath` must be an existing directory or file.'
73
- + `\n'${ inputPath }' does not exist.`);
74
- }
75
-
76
- // Validate options
77
- for (const key of Object.keys(options)) {
78
- if (!Object.prototype.hasOwnProperty.call(defaultOptions, key)) return console.error(
79
- `findSCSS() error: \`${ key }\` is an invalid option.`
80
- + `\nValid options: [ ${Object.keys(defaultOptions).join(', ')} ]`);
81
- else if (typeof options[key] !== 'boolean') return console.error(
82
- `findSCSS() error: \`${ key }\` option must be set to \`true\` or \`false\`.`);
83
- }
84
-
85
- // Compile SCSS based on inputPath
86
- const compileOptions = { style: options.minify ? 'compressed' : 'expanded', sourceMap: options.sourceMaps };
87
- if (fs.existsSync(inputPath)) { // compile based on path arg
88
- if (inputPath.endsWith('.scss')) { // file path passed
89
- if (options.verbose) console.info(`Compiling ${ inputPath }...`);
90
- try { // to compile file passed
91
- const compileResult = sass.compile(inputPath, compileOptions);
92
- return { code: compileResult.css, srcMap: compileResult.sourceMap,
93
- srcPath: path.resolve(process.cwd(), inputPath) };
94
- } catch (err) { console.error(`\nERROR: ${ err.message }\n`); return { error: err }; }
95
- } else { // dir path passed
96
- return findSCSS(inputPath, { recursive: options.recursive, verbose: options.verbose,
97
- dotFolders: options.dotFolders
98
- })?.map(scssPath => { // compile found SCSS files
99
- if (options.verbose) console.info(`Compiling ${ scssPath }...`);
100
- try { // to compile found file
101
- const compileResult = sass.compile(scssPath, compileOptions);
102
- return { code: compileResult.css, srcMap: compileResult.sourceMap, srcPath: scssPath };
103
- } catch (err) { console.error(`\nERROR: ${ err.message }\n`); return { error: err }; }
104
- }).filter(data => !data.error ); // filter out failed compilations
105
- }
106
- }
107
- }
108
-
109
- // EXPORT main functions if script was required
110
- if (require.main !== module) module.exports = { compile, findSCSS };
111
-
112
- else { // run as CLI utility
113
-
114
- // Init UI colors
115
- const nc = '\x1b[0m', // no color
116
- br = '\x1b[1;91m', // bright red
117
- by = '\x1b[1;33m', // bright yellow
118
- bg = '\x1b[1;92m'; // bright green
119
-
120
- // Load FLAG settings
121
- const config = {};
122
- const argRegex = {
123
- 'dryRun': /^--?(?:n|dry-?run)$/,
124
- 'includeDotFolders': /^--?(?:dd?|(?:include-?)?dot-?(?:folder|dir(?:ector(?:y|ie))?)s?=?(?:true|1)?)$/,
125
- 'noSourceMaps': /^--?(?:S|(?:exclude|disable|no)-?so?u?rce?-?maps?|so?u?rce?-?maps?=(?:false|0))$/,
126
- 'noRecursion': /^--?(?:R|(?:disable|no)-?recursion|recursion=(?:false|0))$/,
127
- 'noMinify': /^--?(?:M|(?:disable|no)-?minif(?:y|ication)|minif(?:y|ication)=(?:false|0))$/,
128
- 'quietMode': /^--?q(?:uiet)?(?:-?mode)?$/,
129
- 'help': /^--?h(?:elp)?$/,
130
- 'version': /^--?ve?r?s?i?o?n?$/
131
- };
132
- process.argv.forEach(arg => {
133
- if (!arg.startsWith('-')) return;
134
- const matchedFlag = Object.keys(argRegex).find(flag => argRegex[flag].test(arg));
135
- if (matchedFlag) config[matchedFlag] = true;
136
- else {
137
- console.error(`\n${br}ERROR: Arg [${ arg }] not recognized.${nc}`);
138
- console.info(`\n${by}Valid arguments are below.${nc}`);
139
- printHelpSections(['configOptions', 'infoCmds']);
140
- process.exit(1);
141
- }});
142
-
143
- // Show HELP screen if -h or --help passed
144
- if (process.argv.some(arg => argRegex.help.test(arg))) printHelpSections();
145
-
146
- // Show VERSION number if -v or --version passed
147
- else if (process.argv.some(arg => argRegex.version.test(arg)))
148
- console.info('v' + require('./package.json').version);
149
-
150
- else { // run MAIN routine
151
-
152
- // Init I/O args
153
- const [inputArg = '', outputArg = ''] = ( // default to empty strings for error-less handling
154
- process.argv.slice(2) // exclude executable and script paths
155
- .filter(arg => !arg.startsWith('-')) // exclude flags
156
- .map(arg => arg.replace(/^\/*/, '')) // clean leading slashes to avoid parsing system root
157
- );
158
-
159
- // Validate input arg (output arg can be anything)
160
- const inputPath = path.resolve(process.cwd(), inputArg);
161
- if (inputArg && !fs.existsSync(inputPath)) {
162
- console.error(`\n${br}Error: First argument must be an existing file or directory.`
163
- + `\n'${ inputPath }' does not exist.${nc}`
164
- + `\n\n${bg}Example valid command: \n>> scss-to-css . output.min.css${nc}`
165
- + `\n\n${by}For all command options: \n>> scss-to-css --help${nc}`);
166
- process.exit(1);
167
- }
168
-
169
- // Find all eligible JavaScript files or arg-passed file
170
- const scssFiles = inputArg.endsWith('.scss') ? [inputPath]
171
- : findSCSS(inputPath, { recursive: !config.noRecursion, verbose: !config.quietMode });
172
-
173
- if (config.dryRun) { // -n or --dry-run passed
174
- if (scssFiles.length > 0) { // print files to be processed
175
- console.info(`\n${by}SCSS files to be compiled:${nc}`);
176
- scssFiles.forEach(file => console.info(file));
177
- } else console.info(`${by}\nNo SCSS files will be compiled.${nc}`);
178
-
179
- } else { // actually compile SCSS files
180
-
181
- // Build array of compilation data
182
- const failedPaths = [];
183
- const compileData = scssFiles.map(scssPath => {
184
- const compileResult = compile(scssPath, {
185
- minify: !config.noMinify, sourceMaps: !config.noSourceMaps, verbose: !config.quietMode });
186
- if (compileResult.error) failedPaths.push(scssPath);
187
- return compileResult;
188
- }).filter(data => !data.error ); // filter out failed compilations
189
-
190
- // Write array data to files
191
- compileData?.forEach(({ code, srcMap, srcPath }) => {
192
- const outputDir = path.join(
193
- path.dirname(srcPath), // path of file to be minified
194
- /(?:src|s[ac]ss)$/.test(path.dirname(srcPath)) ? '../css' // + ../css/ if in *(src|sass|scss)/
195
- : outputArg.endsWith('.css') ? path.dirname(outputArg) // or path from file output arg
196
- : outputArg || 'css' // or path from folder output arg or css/ if no output arg passed
197
- );
198
- const outputFilename = (
199
- outputArg.endsWith('.css') && inputArg.endsWith('.scss')
200
- ? path.basename(outputArg).replace(/(\.min)?\.css$/, '')
201
- : path.basename(srcPath, '.scss')
202
- ) + '.min.css';
203
- const outputPath = path.join(outputDir, outputFilename);
204
- if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
205
- fs.writeFileSync(outputPath, code, 'utf8');
206
- if (!config.noSourceMaps) fs.writeFileSync(outputPath + '.map', JSON.stringify(srcMap), 'utf8');
207
- });
208
-
209
- // Print final summary
210
- if (compileData?.length > 0) {
211
- const cssCntSuffix = compileData.length > 1 ? 's' : '';
212
- printIfNotQuiet(`\n${bg}Compilation complete!${nc}`);
213
- printIfNotQuiet(`${ compileData.length } CSS file${ cssCntSuffix }`
214
- + ( !config.noSourceMaps ? ` + ${ compileData.length } source map${ cssCntSuffix }` : '' )
215
- + ' generated.');
216
- } else printIfNotQuiet(`${by}No SCSS files processed.${nc}`);
217
- if (failedPaths.length > 0) {
218
- printIfNotQuiet(`\n${br}`
219
- + `${ failedPaths.length } file${ failedPaths.length > 1 ? 's' : '' }`
220
- + ` failed to compile:${nc}`);
221
- failedPaths.forEach(path => printIfNotQuiet(path));
222
- }
223
- }
224
- }
225
-
226
- // Define LOGGING functions
227
-
228
- function printHelpSections(includeSections = ['cmdFormat', 'pathArgs', 'configOptions', 'infoCmds']) {
229
- const helpSections = {
230
- 'cmdFormat': [
231
- `\n${by}scss-to-css [inputPath] [outputPath] [options]${nc}`
232
- ],
233
- 'pathArgs': [
234
- '\nPath arguments:',
235
- ' [inputPath] '
236
- + 'Path to SCSS file or directory containing SCSS files to be compiled,'
237
- + ' relative to the current working directory.',
238
- ' [outputPath] '
239
- + 'Path to file or directory where CSS + sourcemap files will be stored,'
240
- + ' relative to original file location (if not provided, css/ is used).'
241
- ],
242
- 'configOptions': [
243
- '\nConfig options:',
244
- ' -n, --dry-run Don\'t actually compile the file(s),'
245
- + ' just show if they will be processed.',
246
- ' -d, --include-dotfolders Include dotfolders in file search.',
247
- ' -S, --no-source-maps Prevent source maps from being generated.',
248
- ' -M, --no-minify Disable minification of output CSS.',
249
- ' -R, --no-recursion Disable recursive file searching.',
250
- ' -q, --quiet Suppress all logging except errors.'
251
- ],
252
- 'infoCmds': [
253
- '\nInfo commands:',
254
- ' -h, --help Display help screen.',
255
- ' -v, --version Show version number.'
256
- ]
257
- };
258
- includeSections.forEach(section => { // print valid arg elems
259
- helpSections[section]?.forEach(line => printHelpMsg(line)); });
260
-
261
- function printHelpMsg(msg) { // wrap msg + indent 2nd+ lines (for --help screen)
262
- const terminalWidth = process.stdout.columns || 80,
263
- indentation = 30, lines = [], words = msg.match(/\S+|\s+/g);
264
-
265
- // Split msg into lines of appropriate lengths
266
- let currentLine = '';
267
- words.forEach(word => {
268
- const lineLength = terminalWidth - ( lines.length === 0 ? 0 : indentation );
269
- if (currentLine.length + word.length > lineLength) { // cap/store it
270
- lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
271
- currentLine = '';
272
- }
273
- currentLine += word;
274
- });
275
- lines.push(lines.length === 0 ? currentLine : currentLine.trimStart());
276
-
277
- // Print formatted msg
278
- lines.forEach((line, index) => console.info(
279
- index === 0 ? line // print 1st line unindented
280
- : ' '.repeat(indentation) + line // print subsequent lines indented
281
- ));
282
- }
283
- }
284
-
285
- function printIfNotQuiet(msg) { if (!config.quietMode) console.info(msg); }
286
- }