Skip to content

Commit

Permalink
reduce matched selectors, fix broken examples #18
Browse files Browse the repository at this point in the history
  • Loading branch information
tbela99 committed Aug 10, 2024
1 parent 9c2bf3f commit ee41fed
Show file tree
Hide file tree
Showing 13 changed files with 630 additions and 220 deletions.
36 changes: 20 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,36 @@ Extract critical CSS path for the current viewport in the current page.

Using modules
```html

<script type="module">
import {parse, render} from 'https://esm.sh/@tbela99/css-parser/web';
import {extract} from 'https://esm.sh/tbela99/critical/browser';
const result = await extract({ fonts: true });
import {parse, render} from 'https://esm.sh/@tbela99/css-parser@0.6.0/web';
import {extract} from 'https://esm.sh/@tbela99/critical@1.1.0/browser';
const results = await extract({fonts: true});
// css is optimized using https://www.npmjs.com/package/@tbela99/css-parser
// pretty print css
const css = await parse(results.styles.join('\n')).then(result => render(result.ast, {minify: false}).code);
console.debug(css);
</script>
```

Without using modules
```html

<script src="./dist/browser-umd.js"></script>
<script src="https://cdn.jsdelivr.net/gh/tbela99/css-parser/dist/index-umd-web.js"></script>
<script src="https://cdn.jsdelivr.net/gh/tbela99/critical@1.1.0/dist/browser-umd.js"></script>
<script src="https://cdn.jsdelivr.net/gh/tbela99/css-parser@0.6.0/dist/index-umd-web.js"></script>
<script>
const {parse, render} = CSSParser;
const {extract} = critical;
const result = await extract({fonts: true});
// optimize and pretty print css
const css = await parse(results.styles.join('\n')).then(result => render(result.ast, {minify: false}).code);
(async () => {
console.debug(css);
const {parse, render} = CSSParser;
const results = await critical.extract({fonts: true});
// optimize and pretty print css
const css = await parse(results.styles.join('\n')).then(result => render(result.ast, {minify: false}).code);
console.debug(css);
})();
</script>
```

Expand Down Expand Up @@ -75,7 +74,8 @@ urls.forEach(async url => critical(url, {
screenshot: true,
secure: false,
// dimensions can be specified as an array of string or object
dimensions: ['1400x900', '1200x675', '992x558']
dimensions: ['1400x900', '1200x675', '992x558'],
advanced: true
}).then((results) => {

// print extracted CSS
Expand Down Expand Up @@ -111,6 +111,7 @@ urls.forEach(async url => critical(url, {
- output: _string_. change output directory. default _'./output/'_
- fonts: _bool_. generate javascript to load web fonts. default _true_
- json: _bool_. dump result as JSON
- advanced: _bool_. remove parts of css selectors that do not match any element. default _false_
> debugging settings
- console: _bool_. log console messages from the pages. default _true_
- verbose: _bool_. enable verbose mode
Expand Down Expand Up @@ -161,6 +162,8 @@ Options:
-p, --html Generate an HTML page containing inlined critical css
[boolean]
--json print result in JSON format [boolean] [default: false]
-e, --advanced remove parts of css selectors that do not match any elem
ent [boolean] [default: false]
-v, --verbose Enable verbose mode [boolean] [default: false]


Expand All @@ -185,6 +188,7 @@ $ cat pages/dashboard.html | critical-cli --base=pages/ --secure=no -i -d '1440x
### V1.1.0

- read data from STDIN
- remove unused selectors
- dump cli result as JSON

### V1.0.1
Expand Down
9 changes: 8 additions & 1 deletion bin/args.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,14 @@
"description": "print result in JSON format",
"type": "boolean",
"default": false
} ,
},
"advanced": {
"alias": "e",
"demandOption": false,
"description": "remove parts of css selectors that do not match any element",
"type": "boolean",
"default": false
},
"verbose": {
"alias": "v",
"demandOption": false,
Expand Down
38 changes: 23 additions & 15 deletions bin/critical-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,39 @@ const aliases = new Map;

aliases.set('h', 'help');

for (const [name, command] of Object.entries(cliArgs.args)) {
try {

if (aliases.has(command.alias)) {
for (const [name, command] of Object.entries(cliArgs.args)) {

throw new Error(`'${name}': Alias ${command.alias} already in use by ${aliases.get(command.alias)}'`);
if (aliases.has(command.alias)) {

throw new Error(`'${name}': Alias ${command.alias} already in use by ${aliases.get(command.alias)}'`);
}

aliases.set(command.alias, name);
aliases.set(name.replace(/-([a-z])/g, (all, one) => one.toUpperCase()), name);
_yargs.option(name, command);
}

aliases.set(command.alias, name);
aliases.set(name.replace(/-([a-z])/g, (all, one) => one.toUpperCase()), name);
_yargs.option(name, command);
}
for (const name of Object.keys(_yargs.argv)) {

if (name === '_' || '$0' === name) {

for (const name of Object.keys(_yargs.argv)) {
continue;
}

if (name === '_' || '$0' === name) {
if (!aliases.has(name.replace(/-([a-z])/g, (all, one) => one.toUpperCase()))) {

continue;
throw new Error(`'${name}': Unknown argument`);
}
}
}

if (!aliases.has(name.replace(/-([a-z])/g, (all, one) => one.toUpperCase()))) {
catch (error) {

throw new Error(`'${name}': Unknown argument`);
}
_yargs.showHelp();
console.error(error.message);
process.exit(1);
}

_yargs.help().alias('help', 'h') /*.strict(true) */;
Expand All @@ -52,7 +62,6 @@ for (let key of Object.keys(options)) {
}
}


// @ts-ignore
delete options._;
// @ts-ignore
Expand All @@ -64,7 +73,6 @@ if (urls.length === 0 && process.stdin.isTTY) {
process.exit();
}


if (process.stdin.isTTY == null) {

urls.length = 0;
Expand Down
2 changes: 2 additions & 0 deletions dist/browser-umd.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/browser-umd.js.map

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions dist/browser.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/browser.js.map

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion dist/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ interface CriticalOptions {
url?: string;
input?: string;
headless?: boolean;
advanced?: boolean;
browser?: BrowserOptions;
browserType?: 'mobile' | 'desktop' | 'default';
base?: string;
Expand Down Expand Up @@ -66,5 +67,7 @@ interface CriticalCliResult {

declare function critical(options: CriticalOptions): Promise<CriticalCliResult>;
declare function critical(url: string, options: CriticalOptions): Promise<CriticalCliResult>;
declare function isWhiteSpace(codepoint: number): boolean;
declare function splitRule(buffer: string): string[][];

export { critical };
export { critical, isWhiteSpace, splitRule };
Loading

0 comments on commit ee41fed

Please sign in to comment.