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 f32e75f commit 7a6ce7a
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 86 deletions.
1 change: 1 addition & 0 deletions .github/workflows/add-tag.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
npm dist-tag add @blockquote/[email protected] latest
19 changes: 12 additions & 7 deletions bin/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
#!/usr/bin/env node

const fs = require('fs');
const { program } = require('commander');
const path = require('path');
const pkg = require('../package.json');
import fs from 'fs';
import { program } from 'commander';
import { SassStyleTemplate } from '../lib/index.js';
import path from 'path';
import { fileURLToPath } from 'url';

const SassStyleTemplate = require('../lib/index.js');
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const customTemplate = path.resolve('.sass-template.tmpl');
const pkgPath = path.resolve(__dirname, '../package.json');
const customTemplate = path.resolve(__dirname, '../.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 @@ -25,6 +30,6 @@ const template = fs.existsSync(customTemplate)
? fs.readFileSync(customTemplate, 'utf8')
: undefined;

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

new SassStyleTemplate(config);
127 changes: 52 additions & 75 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const fs = require('fs');
const glob = require('glob');
const sass = require('sass');
const path = require('path');
const chokidar = require('chokidar');
const mkdirp = require('mkdirp');
const autoprefixer = require('autoprefixer');
const postcss = require('postcss');
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',
Expand All @@ -17,7 +20,7 @@ const color = {

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

class SassStyleTemplate {
export class SassStyleTemplate {
constructor({
markerStart = 'const styles = css`',
markerEnd = '`;',
Expand All @@ -26,8 +29,8 @@ class SassStyleTemplate {
woSuffix = undefined,
jsFile = 'js',
destination = undefined,
template = fs.readFileSync(
`${__dirname}/../tpls/sass-template.tmpl`,
template = fs.readFile(
path.join(__dirname, 'tpls/sass-template.tmpl'),
'utf8'
),
} = {}) {
Expand All @@ -41,42 +44,43 @@ class SassStyleTemplate {
destination,
template,
};
this.globFiles = glob.sync(`{${this.options.customGlob},}`);

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

this.init();
}

processCss(css) {
return postcss([autoprefixer]).process(css).css;
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) {
const errL = `${color.red}${err}${color.reset}`;
console.info(errL);
console.error(`${color.red}${err}${color.reset}`);
}
}

get fileInfo() {
return this._fileInfo;
}

set fileInfo(fileInfo = {}) {
this._fileInfo = fileInfo;
set fileInfo(fileInfo) {
this._fileInfo = fileInfo || {};
}

get globFiles() {
return this._globFiles;
}

set globFiles(files = []) {
this._globFiles = files;
set globFiles(files) {
this._globFiles = files || [];
}

cleanDestinationPath() {
async cleanDestinationPath() {
const strBase = this.options.destination;
const firstCharacter = strBase.charAt(0);
const lastCharacter = strBase.charAt(strBase.length - 1);
Expand All @@ -87,20 +91,17 @@ class SassStyleTemplate {
if (lastCharacter === path.sep) {
strFinal = strFinal.slice(0, strFinal.length - 1);
}
mkdirp.sync(strFinal);

return `${path.resolve(strFinal)}`;
await fs.mkdir(strFinal, { recursive: true });
return path.resolve(strFinal);
}

writeTemplate(fileName, cssResult) {
fs.writeFileSync(fileName, cssResult, 'utf8');
const relL = `${color.BrightCyan}[sass]${color.green} reload`;
const filL = `${color.grey}${this.fileInfo.fileNameWithoutExt}${this.fileInfo.fileExt}${color.reset}`;
console.info(`${relL} ${filL}`);
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}`);
}

renderStylesTemplate(fileName) {
const cssResult = this.processCss(this.processSass(fileName));
async renderStylesTemplate(fileName) {
const cssResult = await this.processCss(this.processSass(fileName));

if (path.basename(fileName).charAt(0) === '_') {
return;
Expand All @@ -110,47 +111,33 @@ 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 = Object.assign(this.fileInfo, {
fileDir: path.dirname(fileName),
});
}

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

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

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

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

const content = this.options.template.replace(delimTemplate, cssResult);
return this.writeTemplate(fileNameStyle, content);
}
Expand All @@ -171,30 +158,22 @@ class SassStyleTemplate {
this.unlinkFile(path);
});

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

unlinkFile(file) {
async unlinkFile(file) {
const fileNameWithoutExt = path.basename(file, '.scss');
const fileToUnlink = `${this.fileInfo.fileDir}/${fileNameWithoutExt}${this.fileInfo.fileExt}`;
if (fs.existsSync(fileToUnlink)) {
try {
fs.unlinkSync(fileToUnlink);
const remL = `${color.red}file removed ${path.basename(fileToUnlink)}${
color.reset
}`;
console.info(remL);
} catch (err) {
const errL = `${color.red}${err}${color.reset}`;
console.error(errL);
}
try {
await fs.unlink(fileToUnlink);
console.info(`${color.red}file removed ${path.basename(fileToUnlink)}${color.reset}`);
} catch (err) {
console.error(`${color.red}${err}${color.reset}`);
}
}

updateGlob() {
this.globFiles = glob.sync(`{${this.options.customGlob}}`);
this.globFiles = globSync(this.options.customGlob.split(','));
}

globSassFile(cb) {
Expand All @@ -204,9 +183,7 @@ class SassStyleTemplate {
}

init() {
this.watchSass(this.options.customGlob.split(','));
this.watchSass(this.globFiles);
this.globSassFile(this.renderStylesTemplate);
}
}

module.exports = SassStyleTemplate;
11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@blockquote/sass-style-template",
"version": "3.0.5",
"version": "4.0.0-rc.1",
"description": "SASS and LitElement for creating Web Components",
"keywords": [
"LitElement",
Expand All @@ -19,6 +19,10 @@
"url": "https://github.com/oscarmarina/sass-style-template"
},
"main": "./lib/index.js",
"type": "module",
"files": [
"!.github/"
],
"bin": {
"sass-style-template": "./bin/index.js"
},
Expand All @@ -28,10 +32,9 @@
},
"dependencies": {
"autoprefixer": "^10.4.20",
"chokidar": "^3.6.0",
"chokidar": "^4.0.1",
"commander": "^12.1.0",
"glob": "^11.0.0",
"mkdirp": "^3.0.1",
"tinyglobby": "^0.2.10",
"postcss": "^8.4.47",
"sass": "^1.80.6"
},
Expand Down

0 comments on commit 7a6ce7a

Please sign in to comment.