Angular 6 CLI -> how to make ng build build project + libraries

会有一股神秘感。 提交于 2019-11-30 11:49:12

I just added a script to package.json to do that, could not find a better way.

  "scripts": {
    "build-all": "ng build lib1 && ng build lib2 && ng build",
    "build-all-prod": "ng build lib1 --prod && ng build lib2 --prod && ng build --prod"
  },

and then

yarn run build-all

Currently there is no supported way to do this out of the box. As suggested by @oklymenk you should for now go with a custom script which will chain all these build commands.

Also the link shared by @Eutrepe, you can see that they are planning to get rid of this re build thing everytime you make changes to your library.

Running ng build my-lib every time you change a file is bothersome and takes time.

Some similar setups instead add the path to the source code directly inside tsconfig. This makes seeing changes in your app faster.

But doing that is risky. When you do that, the build system for your app is building the library as well. But your library is built using a different build system than your app.

Those two build systems can build things slightly different, or support completely different features.

This leads to subtle bugs where your published library behaves differently from the one in your development setup.

For this reason we decided to err on the side of caution, and make the recommended usage the safe one.

In the future we want to add watch support to building libraries so it is faster to see changes.

We are also planning to add internal dependency support to Angular CLI. This means that Angular CLI would know your app depends on your library, and automatically rebuilds the library when the app needs it.

Why do I need to build the library everytime I make changes?

Maybe this works for you:

Build the library with ng build --prod --project=your-library, then in your package.json dependencies:

"example-ng6-lib": "file:../example-ng6-lib/dist/example-ng6-lib/example-ng6-lib-0.0.1.tgz",

Then ng build --prod your root project.

Example taken from here: https://blog.angularindepth.com/creating-a-library-in-angular-6-part-2-6e2bc1e14121

I find and test this: https://github.com/angular/angular-cli/wiki/stories-create-library

So instead ng build --prod you should use ng build my-lib --prod

I created a script that, when placed in the same folder as angular.json, will pull in the file, loop over the projects, and build them in batches asynchronously.

Here's a quick gist, you can toggle the output path and the number of asynchronous builds. I've excluded e2e for the moment, but you can remove the reference to the filteredProjects function, and it will run for e2e as projects as well. It would also be easy to add this to package.json as an npm run script. So far, it has been working well.

https://gist.github.com/bmarti44/f6b8d3d7b331cd79305ca8f45eb8997b

const fs = require('fs'),
  spawn = require('child_process').spawn,
  // Custom output path.
  outputPath = '/nba-angular',
  // Number of projects to build asynchronously.
  batch = 3;

let ngCli;

function buildProject(project) {
  return new Promise((resolve, reject) => {
    let child = spawn('ng', ['build', '--project', project, '--prod', '--extract-licenses', '--build-optimizer', `--output-path=${outputPath}/dist/` + project]);

    child.stdout.on('data', (data) => {
      console.log(data.toString());
    });

    child.stderr.on('data', (data) => {
      process.stdout.write('.');
    });

    child.on('close', (code) => {
      if (code === 0) {
        resolve(code);
      } else {
        reject(code);
      }
    });
  })
}

function filterProjects(projects) {
  return Object.keys(projects).filter(project => project.indexOf('e2e') === -1);
}

function batchProjects(projects) {
  let currentBatch = 0,
    i,
    batches = {};

  for (i = 0; i < projects.length; i += 1) {
    if ((i) % batch === 0) {
      currentBatch += 1;
    }
    if (typeof (batches['batch' + currentBatch]) === 'undefined') {
      batches['batch' + currentBatch] = [];
    }

    batches['batch' + currentBatch].push(projects[i]);
  }
  return batches;
}

fs.readFile('angular.json', 'utf8', async (err, data) => {
  let batches = {},
    batchesArray = [],
    i;

  if (err) {
    throw err;
  }

  ngCli = JSON.parse(data);

  batches = batchProjects(filterProjects(ngCli.projects));
  batchesArray = Object.keys(batches);

  for (i = 0; i < batchesArray.length; i += 1) {
    let promises = [];

    batches[batchesArray[i]].forEach((project) => {
      promises.push(buildProject(project));
    });

    console.log('Building projects ' + batches[batchesArray[i]].join(','));

    await Promise.all(promises).then(statusCode => {
      console.log('Projects ' + batches[batchesArray[i]].join(',') + ' built successfully!');
      if (i + 1 === batchesArray.length) {
        process.exit(0);
      }
    }, (reject) => {
      console.log(reject);
      process.exit(1);
    });
  }
});

ng-build already includes your libraries in the main.js bundle. No need to separately build each library.

As much as I know, there is no build-in way to do this in the current version (Angular 8).
It might be possible to use the new builders but I don't know much about them yet.
So what I did instead was to create a script, which reads in the angular.json file and determines all application projects and all configurations.
Then it executes ng build for every project and configuration.
Also, it will collect all the failed builds and log them to the console at the end.
This script looks like this:

import { ProjectType, WorkspaceSchema } from "@schematics/angular/utility/workspace-models";
import { execSync } from "child_process";
import { readFileSync } from "fs";

interface ExecParams {
  project: string;
  config: string;
}

interface ExecError extends ExecParams {
  message: string;
}

function buildAll() {
  const json: WorkspaceSchema = JSON.parse(readFileSync("./angular.json").toString());
  const errors: ExecError[] = Object.keys(json.projects)
    // Filter application-projects
    .filter(name => json.projects[name].projectType === ProjectType.Application)
    // Determine parameters needed for the build command
    .reduce<ExecParams[]>((arr, project) => {
      const proj = json.projects[project];
      let build = proj.architect && proj.architect.build;
      if (build) {
        arr = arr.concat(...Object.keys(build.configurations || {})
          .map(config => ({ project, config }))
        );
      }
      return arr;
    }, [])
    // Execute `ng build` and collect errors.
    .reduce<ExecError[]>((err, exec) => {
      try {
        console.log(`Building ${exec.project} (${exec.config}):`);
        execSync(`ng build --prod --project ${exec.project} --configuration ${exec.config}`, {stdio: "inherit"});
      }
      catch (error) {
        err.push({
          project: exec.project,
          config: exec.config,
          message: error.message
        });
      }
      console.log("\n");
      return err;
    }, []);

  // Conditionally log errors
  if (errors.length === 0)
    console.log("Completed");
  else {
    console.log("\n");
    errors.forEach(error => {
      console.error(`Building ${error.project} (${error.config}) failed:\n\t${error.message}`);
    });
  }
}

buildAll();

You can compile it using tsc and then run it with NodeJs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!