Blog>
Snippets

Scoped Package Publishing from Angular Monorepo

Demonstrating the process of publishing individually versioned packages from an Angular monorepo to a package registry like npm.
const execSync = require('child_process').execSync;
const readPackageJson = require('./read-package-json');

function publishPackage(packagePath) {
  const packageJson = readPackageJson(packagePath);
  if (packageJson.private) {
    console.log(`Skipping private package: ${packageJson.name}`);
    return;
  }
  // Update the version if needed and push tags
  // Your strategy for versioning goes here
  const newVersion = '1.0.0'; // replace with dynamic versioning if necessary
  execSync(`npm version ${newVersion}`, { cwd: packagePath, stdio: 'inherit' });
  // Publish the package to npm registry with the scoped name
  execSync(`npm publish --access public`, { cwd: packagePath, stdio: 'inherit' });
}

// Example Usage:
// Adjust the paths and names according to your monorepo structure
const packagesToPublish = ['./packages/package-a', './packages/package-b'];
packagesToPublish.forEach(publishPackage);
This JS code defines a function named `publishPackage`, which is responsible for publishing a package from a given path to the npm registry. If the package.json file indicates the package as private, it skips publishing. It allows setting a new version before publishing and ensures the package is published with public access. An example usage is also provided, looping over an array of predefined package paths to demonstrate how to invoke the function for multiple packages.
const fs = require('fs');

function readPackageJson(packagePath) {
  const packageJsonPath = `${packagePath}/package.json`;
  if (!fs.existsSync(packageJsonPath)) {
    throw new Error(`package.json not found in the specified path: ${packageJsonPath}`);
  }
  return JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
}

module.exports = readPackageJson;
This JS code is a utility function named `readPackageJson`, used to read and parse the package.json file within a given package path. It verifies that the package.json file exists and then reads the file, parsing the JSON content to return it as an object. The function is exported so it can be used in other parts of the script, such as the `publishPackage` function provided in the previous code snippet.