UNPKG

2.62 kBJavaScriptView Raw
1/*
2 Copyright 2018 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
9const fse = require('fs-extra');
10const path = require('path');
11const errors = require('./errors');
12
13
14// Used to filter the libraries to copy based on our package.json dependencies.
15const WORKBOX_PREFIX = 'workbox-';
16
17/**
18 * This copies over a set of runtime libraries used by Workbox into a
19 * local directory, which should be deployed alongside your service worker file.
20 *
21 * As an alternative to deploying these local copies, you could instead use
22 * Workbox from its official CDN URL.
23 *
24 * This method is exposed for the benefit of developers using
25 * [injectManifest()]{@link module:workbox-build.injectManifest} who would
26 * prefer not to use the CDN copies of Workbox. Developers using
27 * [generateSW()]{@link module:workbox-build.generateSW} don't need to
28 * explicitly call this method, as it's called automatically when
29 * `importWorkboxFrom` is set to `local`.
30 *
31 * @param {string} destDirectory The path to the parent directory under which
32 * the new directory of libraries will be created.
33 * @return {Promise<string>} The name of the newly created directory.
34 *
35 * @alias module:workbox-build.copyWorkboxLibraries
36 */
37module.exports = async (destDirectory) => {
38 const thisPkg = require('../../package.json');
39 // Use the version string from workbox-build in the name of the parent
40 // directory. This should be safe, because lerna will bump workbox-build's
41 // pkg.version whenever one of the dependent libraries gets bumped, and we
42 // care about versioning the dependent libraries.
43 const workboxDirectoryName = `workbox-v${thisPkg.version}`;
44 const workboxDirectoryPath = path.join(destDirectory, workboxDirectoryName);
45 await fse.ensureDir(workboxDirectoryPath);
46
47 const copyPromises = [];
48 const librariesToCopy = Object.keys(thisPkg.dependencies).filter(
49 (dependency) => dependency.startsWith(WORKBOX_PREFIX));
50 for (const library of librariesToCopy) {
51 const mainFilePath = require.resolve(library);
52 const srcPath = path.dirname(mainFilePath);
53
54 // fse.copy() copies all the files in a directory, not the directory itself.
55 // See https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md#copysrc-dest-options-callback
56 copyPromises.push(fse.copy(srcPath, workboxDirectoryPath));
57 }
58
59 try {
60 await Promise.all(copyPromises);
61 return workboxDirectoryName;
62 } catch (error) {
63 throw Error(`${errors['unable-to-copy-workbox-libraries']} ${error}`);
64 }
65};