Test Failed
Branch develop (785de4)
by Andrew
02:36
created

src/index.ts   A

Complexity

Total Complexity 10
Complexity/F 5

Size

Lines of Code 84
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 64
mnd 8
bc 8
fnc 2
dl 0
loc 84
bpm 4
cpm 5
noi 0
c 0
b 0
f 0
rs 10

1 Function

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