Passed
Push — develop ( 12584e...52ae0e )
by Andrew
03:02
created

src/index.ts   A

Complexity

Total Complexity 8
Complexity/F 4

Size

Lines of Code 79
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 0
Metric Value
wmc 8
eloc 61
mnd 6
bc 6
fnc 2
dl 0
loc 79
ccs 22
cts 24
cp 0.9167
rs 10
bpm 3
cpm 4
noi 0
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
B index.ts ➔ PluginCritical 0 41 8
1
import {Plugin} from 'rollup';
2 1
import path from 'path';
3 1
const critical = require('critical');
4
5 1
const criticalSuffix = '_critical.min.css';
6
7 1
const defaultCriticalConfig = {
8
  inline: false,
9
  minify: true,
10
  extract: false,
11
  width: 1200,
12
  height: 1200,
13
  concurrency: 4,
14
  penthouse: {
15
    blockJSRequests: false
16
  }
17
};
18
19
interface CriticalPages {
20
  uri: string;
21
  template: string;
22
}
23
24
interface CriticalPluginConfig {
25
  criticalUrl: string;
26
  criticalBase?: string;
27
  criticalPages: Partial<CriticalPages>[];
28
  criticalConfig?: Partial<CriticalConfig>;
29
}
30
31
function PluginCritical(pluginConfig: CriticalPluginConfig, callback?: Function): Plugin {
32 1
  return {
33
    name: 'critical',
34
    async writeBundle(outputOptions, bundle) {
35 1
      const css: Array<string> = [];
36
      // Find all of the generated CSS assets
37 1
      for (const chunk of Object.values(bundle)) {
38 4
        if (chunk.type === 'asset' && chunk.fileName.endsWith('.css')) {
39 2
          const cssFile = path.join(outputOptions.dir || '', chunk.fileName);
40 1
          css.push(cssFile);
41
        }
42
      }
43
      // If we have no CSS, skip bundle
44 2
      if (!css.length) {
45
        return;
46
      }
47
      // Iterate through the pages
48 1
      for (const page of pluginConfig.criticalPages) {
49 1
        const criticalBase = pluginConfig.criticalBase;
50 1
        const criticalSrc = pluginConfig.criticalUrl + page.uri;
51 1
        const criticalDest = page.template + criticalSuffix;
52
        // Merge in our options
53 1
        const options = Object.assign(
54
            { css },
55
            defaultCriticalConfig,
56
            {
57
              base: criticalBase,
58
              src: criticalSrc,
59
              target: criticalDest,
60
            },
61
            pluginConfig.criticalConfig
62
        );
63
        // Generate the Critical CSS
64 1
        console.log(`Generating critical CSS from ${criticalSrc} to ${criticalDest}`);
65 1
        await critical.generate(options, (err: string) => {
66 2
          if (err) {
67
            console.error(err);
68
          }
69 2
          if (callback) {
70 1
            callback(err);
71
          }
72
        });
73
      }
74
    }
75
  }
76
};
77
78
export default PluginCritical
79