Angular 4项目指定路径执行ng serve报错:node_modules为空
Hey there! The issue here is that ng serve doesn't treat the path you pass as the project directory to switch into. Instead, it always looks for your project's dependencies (like node_modules) and config files (angular.json, package.json) in your current working directory. When you run ng serve /hardware/angular-src from root, the CLI is still checking /root for node_modules—which is empty, hence the error.
Quick Fixes
1. Switch to the Project Directory First (Most Straightforward)
You can combine the directory switch and serve command into one line so you don't have to do two separate steps:
cd /hardware/angular-src && ng serve
This works exactly like when you manually navigate to the folder first—it tells your terminal to move into the project directory before running ng serve.
2. Use the --cwd Flag (Angular CLI 8+)
If you prefer not to switch directories manually, Angular CLI added the --cwd flag in version 8 to let you specify the working directory directly. Run this from root:
ng serve --cwd /hardware/angular-src
This tells the CLI to execute the command as if you were already inside /hardware/angular-src, so it'll find your node_modules and config files correctly.
3. Use npm Scripts for Repeated Use (Optional)
If you start this project often, you can set up a quick npm script to make it even easier. Open your project's package.json (located at /hardware/angular-src/package.json) and add a start script if it doesn't already exist:
"scripts": { "start": "ng serve", // keep any other existing scripts here }
Then, from root, you can run:
npm start --prefix /hardware/angular-src
The --prefix flag tells npm to run the script from the specified directory.
内容的提问来源于stack exchange,提问作者Sithys

