| 1 | /*
|
|---|
| 2 | Copyright 2019 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 |
|
|---|
| 9 | import upath from 'upath';
|
|---|
| 10 | import {Compilation, WebpackError} from 'webpack';
|
|---|
| 11 |
|
|---|
| 12 | import {resolveWebpackURL} from './resolve-webpack-url';
|
|---|
| 13 |
|
|---|
| 14 | export function getScriptFilesForChunks(
|
|---|
| 15 | compilation: Compilation,
|
|---|
| 16 | chunkNames: Array<string>,
|
|---|
| 17 | ): Array<string> {
|
|---|
| 18 | const {chunks} = compilation.getStats().toJson({chunks: true});
|
|---|
| 19 | const {publicPath} = compilation.options.output;
|
|---|
| 20 | const scriptFiles = new Set<string>();
|
|---|
| 21 |
|
|---|
| 22 | for (const chunkName of chunkNames) {
|
|---|
| 23 | const chunk = chunks!.find((chunk) => chunk.names?.includes(chunkName));
|
|---|
| 24 | if (chunk) {
|
|---|
| 25 | for (const file of chunk?.files ?? []) {
|
|---|
| 26 | // See https://github.com/GoogleChrome/workbox/issues/2161
|
|---|
| 27 | if (upath.extname(file) === '.js') {
|
|---|
| 28 | scriptFiles.add(resolveWebpackURL(publicPath as string, file));
|
|---|
| 29 | }
|
|---|
| 30 | }
|
|---|
| 31 | } else {
|
|---|
| 32 | compilation.warnings.push(
|
|---|
| 33 | new Error(
|
|---|
| 34 | `${chunkName} was provided to ` +
|
|---|
| 35 | `importScriptsViaChunks, but didn't match any named chunks.`,
|
|---|
| 36 | ) as WebpackError,
|
|---|
| 37 | );
|
|---|
| 38 | }
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | if (scriptFiles.size === 0) {
|
|---|
| 42 | compilation.warnings.push(
|
|---|
| 43 | new Error(
|
|---|
| 44 | `There were no assets matching ` +
|
|---|
| 45 | `importScriptsViaChunks: [${chunkNames.join(' ')}].`,
|
|---|
| 46 | ) as WebpackError,
|
|---|
| 47 | );
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | return Array.from(scriptFiles);
|
|---|
| 51 | }
|
|---|