Angular 6 CLI:如何通过ng build同时构建项目与库?
Great question! I’ve run into this exact scenario before—when you have a main app and a library in the same workspace, the default ng build only targets the defaultProject set in angular.json. Here are the two most reliable ways to build everything in one go:
1. Specify Multiple Projects Directly in the ng build Command
Angular CLI lets you pass multiple project names to the build command using the --projects flag (or -p for short). Just list all the projects you want to build, separated by commas.
For example, if your main app is my-project, library is my-library, and e2e project is my-project-e2e, run:
ng build --projects my-library,my-project,my-project-e2e
Pro tip: Build the library first! Since your main app likely depends on the library’s compiled output, putting the library first ensures it’s ready before the app tries to reference it.
2. Create a Custom NPM Script (For Repeated Use)
If you find yourself running this command often, adding a custom script to your package.json will save you time. Open your package.json and add a new entry under the scripts section:
"scripts": { "build:all": "ng build my-library && ng build my-project && ng build my-project-e2e" }
Now you can build everything with a single, simple command:
npm run build:all
This approach is cleaner and easier to remember, especially if you have more than a couple of projects to build.
Why the Default ng build Only Builds One Project
As you noticed, the defaultProject setting in angular.json tells the CLI which project to target when you run ng build without any arguments. Changing it to my-library switches the default, but that’s not ideal if you need to build both regularly. The above methods avoid having to toggle this setting back and forth.
内容的提问来源于stack exchange,提问作者dendimiiii

