Skip to content

Commit

Permalink
chore: remove require
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarmarina committed Nov 9, 2024
1 parent 7a6ce7a commit 54e9257
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 68 deletions.
6 changes: 3 additions & 3 deletions bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ const __dirname = path.dirname(__filename);

const pkgPath = path.resolve(__dirname, '../package.json');
const customTemplate = path.resolve(__dirname, '../.sass-template.tmpl');

const tplTemplate = path.resolve(__dirname, '../tpls/sass-template.tmpl');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
console.log('=>:', pkg.version);

program
.version(pkg.version, '-v, --version', 'show version number')
.option('-s, --marker-start <string>', 'start replace position')
Expand All @@ -28,7 +28,7 @@ program.parse(process.argv);

const template = fs.existsSync(customTemplate)
? fs.readFileSync(customTemplate, 'utf8')
: undefined;
: fs.readFileSync(tplTemplate, 'utf8');

const config = Object.assign({}, program.opts(), { template });

Expand Down
177 changes: 115 additions & 62 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@ import fs from 'fs/promises';
import path from 'path';
import { globSync } from 'tinyglobby';
import chokidar from 'chokidar';
import { fileURLToPath } from 'url';
import * as sass from 'sass';
import autoprefixer from 'autoprefixer';
import postcss from 'postcss';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.join(__filename, '../..');

const color = {
reset: '\x1b[0m',
BrightCyan: '\x1b[96m',
Expand All @@ -20,6 +16,64 @@ const color = {

const delimTemplate = /<%\s*content\s*%>/;

class SassProcessor {
async compile(file) {
try {
const result = sass.compile(file);
return result.css;
} catch (error) {
console.error(`Error compiling SASS file ${file}:`, error);
return null;
}
}
}

class CssProcessor {
async autoprefix(css) {
try {
const result = await postcss([autoprefixer]).process(css, {
from: undefined,
});
return result.css;
} catch (error) {
console.error(`Error processing CSS with autoprefixer:`, error);
return null;
}
}
}

class FileHandler {
constructor(destination) {
this.destination = destination || '';
}

async cleanDestinationPath() {
const strBase = this.destination;
const firstCharacter = strBase.charAt(0);
const lastCharacter = strBase.charAt(strBase.length - 1);
let strFinal = strBase;
if (firstCharacter === path.sep) {
strFinal = strFinal.slice(1);
}
if (lastCharacter === path.sep) {
strFinal = strFinal.slice(0, strFinal.length - 1);
}
await fs.mkdir(strFinal, { recursive: true });
return path.resolve(strFinal);
}

async writeTemplate(fileName, cssResult) {
try {
await fs.writeFile(fileName, cssResult, 'utf8');
console.info(
`${color.BrightCyan}[sass]${color.green} reload ${color.grey}${fileName}${color.reset}`
);
} catch (error) {
console.error(`Error writing template to file ${fileName}:`, error);
}
}
}

export class SassStyleTemplate {
constructor({
markerStart = 'const styles = css`',
Expand All @@ -29,10 +83,10 @@ export class SassStyleTemplate {
woSuffix = undefined,
jsFile = 'js',
destination = undefined,
template = fs.readFile(
path.join(__dirname, 'tpls/sass-template.tmpl'),
'utf8'
),
template = '',
sassProcessor = new SassProcessor(),
cssProcessor = new CssProcessor(),
fileHandler = new FileHandler(destination),
} = {}) {
this.options = {
markerStart,
Expand All @@ -44,26 +98,14 @@ export class SassStyleTemplate {
destination,
template,
};

this.sassProcessor = sassProcessor;
this.cssProcessor = cssProcessor;
this.fileHandler = fileHandler;
this.globFiles = globSync(this.options.customGlob.split(','));

this.init();
}

async processCss(css) {
const result = await postcss([autoprefixer]).process(css, { from: undefined });
return result.css;
}

processSass(file) {
try {
const result = sass.compile(file);
return result.css;
} catch (err) {
console.error(`${color.red}${err}${color.reset}`);
}
}

get fileInfo() {
return this._fileInfo;
}
Expand All @@ -80,28 +122,18 @@ export class SassStyleTemplate {
this._globFiles = files || [];
}

async cleanDestinationPath() {
const strBase = this.options.destination;
const firstCharacter = strBase.charAt(0);
const lastCharacter = strBase.charAt(strBase.length - 1);
let strFinal = strBase;
if (firstCharacter === path.sep) {
strFinal = strFinal.slice(1);
}
if (lastCharacter === path.sep) {
strFinal = strFinal.slice(0, strFinal.length - 1);
async renderStylesTemplate(fileName) {
const rawCss = await this.sassProcessor.compile(fileName);

if (!rawCss) {
return;
}
await fs.mkdir(strFinal, { recursive: true });
return path.resolve(strFinal);
}

async writeTemplate(fileName, cssResult) {
await fs.writeFile(fileName, cssResult, 'utf8');
console.info(`${color.BrightCyan}[sass]${color.green} reload ${color.grey}${this.fileInfo.fileNameWithoutExt}${this.fileInfo.fileExt}${color.reset}`);
}
const cssResult = await this.cssProcessor.autoprefix(rawCss);

async renderStylesTemplate(fileName) {
const cssResult = await this.processCss(this.processSass(fileName));
if (!cssResult) {
return;
}

if (path.basename(fileName).charAt(0) === '_') {
return;
Expand All @@ -111,35 +143,52 @@ export class SassStyleTemplate {
fileNameWithoutExt: path.basename(fileName, '.scss'),
fileExt: this.options.cssFile
? `${this.options.woSuffix ? '' : '-styles'}.css`
: `${this.options.woSuffix ? '' : '-styles'}.css.${this.options.jsFile}`,
: `${this.options.woSuffix ? '' : '-styles'}.css.${
this.options.jsFile
}`,
};

if (!this.options.destination) {
this.fileInfo = { ...this.fileInfo, fileDir: path.dirname(fileName) };
} else {
this.fileInfo = { ...this.fileInfo, fileDir: await this.cleanDestinationPath() };
this.fileInfo = {
...this.fileInfo,
fileDir: await this.fileHandler.cleanDestinationPath(),
};
}

const fileNameStyle = `${this.fileInfo.fileDir}/${this.fileInfo.fileNameWithoutExt}${this.fileInfo.fileExt}`;
if (this.options.cssFile) {
return this.writeTemplate(fileNameStyle, cssResult);
return this.fileHandler.writeTemplate(fileNameStyle, cssResult);
}

const userFileExists = await fs.access(fileNameStyle).then(() => true).catch(() => false);

if (userFileExists) {
const file = await fs.readFile(fileNameStyle, 'utf8');
const startReplacePosition = file.indexOf(this.options.markerStart);
if (startReplacePosition >= 0) {
const content = `${file.substring(0, startReplacePosition + this.options.markerStart.length)}${cssResult}${this.options.markerEnd}\n`;
return this.writeTemplate(fileNameStyle, content);
} else {
throw new Error(`${color.red}No found marker start "${this.options.markerStart}" in file.${color.reset}`);
try {
const userFileExists = await fs
.access(fileNameStyle)
.then(() => true)
.catch(() => false);

if (userFileExists) {
const file = await fs.readFile(fileNameStyle, 'utf8');
const startReplacePosition = file.indexOf(this.options.markerStart);
if (startReplacePosition >= 0) {
const content = `${file.substring(
0,
startReplacePosition + this.options.markerStart.length
)}${cssResult}${this.options.markerEnd}\n`;
return this.fileHandler.writeTemplate(fileNameStyle, content);
} else {
throw new Error(
`${color.red}No found marker start "${this.options.markerStart}" in file.${color.reset}`
);
}
}
}

const content = this.options.template.replace(delimTemplate, cssResult);
return this.writeTemplate(fileNameStyle, content);
const content = this.options.template.replace(delimTemplate, cssResult);
return this.fileHandler.writeTemplate(fileNameStyle, content);
} catch (error) {
console.error(`Error processing file ${fileNameStyle}:`, error);
}
}

watchSass(glob) {
Expand All @@ -153,20 +202,24 @@ export class SassStyleTemplate {
this.updateGlob();
});

watcher.on('unlink', (path) => {
watcher.on('unlink', (filePath) => {
this.updateGlob();
this.unlinkFile(path);
this.unlinkFile(filePath);
});

watcher.on('error', (err) => console.error(`Watcher ${color.red}${err}${color.reset}`));
watcher.on('error', (err) =>
console.error(`Watcher ${color.red}${err}${color.reset}`)
);
}

async unlinkFile(file) {
const fileNameWithoutExt = path.basename(file, '.scss');
const fileToUnlink = `${this.fileInfo.fileDir}/${fileNameWithoutExt}${this.fileInfo.fileExt}`;
try {
await fs.unlink(fileToUnlink);
console.info(`${color.red}file removed ${path.basename(fileToUnlink)}${color.reset}`);
console.info(
`${color.red}file removed ${path.basename(fileToUnlink)}${color.reset}`
);
} catch (err) {
console.error(`${color.red}${err}${color.reset}`);
}
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@blockquote/sass-style-template",
"version": "4.0.0-rc.1",
"version": "4.0.0-rc.2",
"description": "SASS and LitElement for creating Web Components",
"keywords": [
"LitElement",
Expand Down Expand Up @@ -34,9 +34,9 @@
"autoprefixer": "^10.4.20",
"chokidar": "^4.0.1",
"commander": "^12.1.0",
"tinyglobby": "^0.2.10",
"postcss": "^8.4.47",
"sass": "^1.80.6"
"sass": "^1.80.6",
"tinyglobby": "^0.2.10"
},
"publishConfig": {
"access": "public"
Expand Down

0 comments on commit 54e9257

Please sign in to comment.