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