zhangjian
2023-05-30 dabbcc356af21f9f2f88ac69ff07994e6e32e4fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'use strict';
 
const CHUNK_OPTIONS = ['all', 'async'];
 
const getPublicPath = require('./common.js').getPublicPath;
const createResourceHint = require('./resource-hints.js').createResourceHint;
const matches = require('./common.js').matches;
 
const addAsyncChunkResourceHints = (chunks, options) => {
  const getRef = generateRef(options);
  const hints = [];
  chunks
    .filter(chunk => !isInitial(chunk))
    .reduce(
      (files, chunk) => files.concat(chunk.files),
      [])
    .forEach(file => {
      if (optionsMatch(options.preload, file)) {
        hints.push(createResourceHint('preload', getRef(file)));
      } else if (optionsMatch(options.prefetch, file)) {
        hints.push(createResourceHint('prefetch', getRef(file)));
      }
    });
  return hints;
};
 
const isInitial = chunk =>
  chunk.canBeInitial
    ? chunk.canBeInitial()
    : chunk.isInitial
      ? chunk.isInitial()
      : chunk.isInitial;
 
const optionsMatch = (option, file) => {
  return matches(option.chunks, CHUNK_OPTIONS) && matches(file, option.test);
};
 
const generateRef = options => {
  const publicPath = getPublicPath(options);
  return publicPath
    ? file => publicPath + file
    : file => file;
};
 
module.exports = addAsyncChunkResourceHints;