|
| 1 | +/* |
| 2 | + This script prepares the central `build` directory for NPM package creation. |
| 3 | + It first copies all non-code files into the `build` directory, including `package.json`, which |
| 4 | + is edited to adjust entry point paths. These corrections are performed so that the paths align with |
| 5 | + the directory structure inside `build`. |
| 6 | +*/ |
| 7 | + |
| 8 | +import * as fs from 'fs'; |
| 9 | + |
| 10 | +import * as path from 'path'; |
| 11 | + |
| 12 | +const BUILD_DIR = 'build'; |
| 13 | +const ASSETS = ['README.md', 'LICENSE', 'package.json', '.npmignore']; |
| 14 | +const ENTRY_POINTS = ['main', 'module', 'types']; |
| 15 | + |
| 16 | +// check if build dir exists |
| 17 | +try { |
| 18 | + if (!fs.existsSync(path.resolve(BUILD_DIR))) { |
| 19 | + console.error(`Directory ${BUILD_DIR} DOES NOT exist`); |
| 20 | + console.error("This script should only be executed after you've run `yarn build`."); |
| 21 | + process.exit(1); |
| 22 | + } |
| 23 | +} catch (error) { |
| 24 | + console.error(`Error while looking up directory ${BUILD_DIR}`); |
| 25 | + process.exit(1); |
| 26 | +} |
| 27 | + |
| 28 | +// copy non-code assets to build dir |
| 29 | +ASSETS.forEach(asset => { |
| 30 | + const assetPath = path.resolve(asset); |
| 31 | + try { |
| 32 | + if (!fs.existsSync(assetPath)) { |
| 33 | + console.error(`Asset ${asset} does not exist.`); |
| 34 | + process.exit(1); |
| 35 | + } |
| 36 | + fs.copyFileSync(assetPath, path.resolve(BUILD_DIR, asset)); |
| 37 | + } catch (error) { |
| 38 | + console.error(`Error while copying ${asset} to ${BUILD_DIR}`); |
| 39 | + process.exit(1); |
| 40 | + } |
| 41 | +}); |
| 42 | + |
| 43 | +// package.json modifications |
| 44 | +const packageJsonPath = path.resolve(BUILD_DIR, 'package.json'); |
| 45 | +const pkgJson: { [key: string]: unknown } = require(packageJsonPath); |
| 46 | + |
| 47 | +// modify entry points to point to correct paths (i.e. strip out the build directory) |
| 48 | +ENTRY_POINTS.filter(entryPoint => pkgJson[entryPoint]).forEach(entryPoint => { |
| 49 | + pkgJson[entryPoint] = (pkgJson[entryPoint] as string).replace(`${BUILD_DIR}/`, ''); |
| 50 | +}); |
| 51 | + |
| 52 | +delete pkgJson.scripts; |
| 53 | +delete pkgJson.volta; |
| 54 | + |
| 55 | +// write modified package.json to file (pretty-printed with 2 spaces) |
| 56 | +try { |
| 57 | + fs.writeFileSync(packageJsonPath, JSON.stringify(pkgJson, null, 2)); |
| 58 | +} catch (error) { |
| 59 | + console.error(`Error while writing package.json to disk`); |
| 60 | + process.exit(1); |
| 61 | +} |
| 62 | + |
| 63 | +console.log(`\nSuccessfully finished postbuild commands for ${pkgJson.name}`); |
0 commit comments